@@ -39,7 +39,7 @@ private static function checkConnection()
3939 * @param string $uid 用户ID
4040 * @return string 完整的缓存键名
4141 */
42- private static function generateKey (string $ pre , string $ client , string $ uid )
42+ private static function generateKey (string $ pre , string $ client , string $ uid ): string
4343 {
4444 return sprintf ('%s%s:%s ' , $ pre , $ client , $ uid );
4545 }
@@ -79,7 +79,10 @@ public static function generateToken(string $pre, string $client, string $uid, i
7979
8080 self ::safeExecute (function () use ($ cacheKey , $ ttl , $ token ) {
8181 Redis::del ($ cacheKey );
82- $ result = Redis::setex ($ cacheKey , $ ttl , $ token );
82+
83+ // 增加leeway时间到TTL中,确保在宽容时间内Redis缓存仍然存在
84+ $ finalTtl = self ::calculateFinalTtl ($ ttl );
85+ $ result = Redis::setex ($ cacheKey , $ finalTtl , $ token );
8386
8487 if (!$ result ) {
8588 throw new RedisConnectionException ('Redis设置令牌失败 ' );
@@ -112,7 +115,9 @@ public static function refreshToken(string $pre, string $client, string $uid, in
112115 }
113116 }
114117
115- $ result = Redis::setex ($ cacheKey , $ ttl , $ token );
118+ // 增加leeway时间到TTL中,确保在宽容时间内Redis缓存仍然存在
119+ $ finalTtl = self ::calculateFinalTtl ($ ttl );
120+ $ result = Redis::setex ($ cacheKey , $ finalTtl , $ token );
116121 if (!$ result ) {
117122 throw new RedisConnectionException ('Redis刷新令牌失败 ' );
118123 }
@@ -195,17 +200,46 @@ private static function validateRedisParams(int $ttl, string $token): void
195200 }
196201 }
197202
203+ /**
204+ * @desc: 计算包含leeway时间的最终TTL
205+ * @param int $ttl 原始TTL
206+ * @return int 包含leeway时间的最终TTL
207+ */
208+ private static function calculateFinalTtl (int $ ttl ): int
209+ {
210+ // 获取JWT配置中的leeway时间
211+ $ config = self ::getJwtConfig ();
212+ $ leeway = $ config ['leeway ' ] ?? 0 ;
213+
214+ // 返回原始TTL加上leeway时间
215+ return $ ttl + $ leeway ;
216+ }
217+
218+ /**
219+ * @desc: 获取JWT配置
220+ * @return array JWT配置数组
221+ */
222+ private static function getJwtConfig (): array
223+ {
224+ if (function_exists ('config ' )) {
225+ $ config = config ('plugin.tinywan.jwt.app.jwt ' );
226+ if (!empty ($ config )) {
227+ return $ config ;
228+ }
229+ }
230+
231+ // 默认配置
232+ return [
233+ 'leeway ' => 60 ,
234+ ];
235+ }
236+
198237 /**
199238 * @desc: 检查Redis是否可用
200239 * @return bool Redis是否可用
201240 */
202241 public static function isAvailable (): bool
203242 {
204- // 检查是否在测试环境
205- if (defined ('PHPUNIT_RUNNING ' ) || getenv ('APP_ENV ' ) === 'testing ' ) {
206- return false ;
207- }
208-
209243 // 检查Redis类是否可用
210244 if (!class_exists ('support\Redis ' )) {
211245 return false ;
0 commit comments