From 39d4c018e41178f199494002cf43d368bb8ecce3 Mon Sep 17 00:00:00 2001 From: Azure <983547216@qq.com> Date: Wed, 17 Jun 2026 09:23:11 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=94=B9=E5=88=B7=E6=96=B0toke?= =?UTF-8?q?n=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../common/utils/RedisCacheUtil.java | 294 ------------------ .../common/utils/RedisMqUtil.java | 90 ------ .../service/impl/RefreshTokenServiceImpl.java | 24 +- 3 files changed, 21 insertions(+), 387 deletions(-) delete mode 100644 src/main/java/com/webgame/webgamebackend/common/utils/RedisCacheUtil.java delete mode 100644 src/main/java/com/webgame/webgamebackend/common/utils/RedisMqUtil.java diff --git a/src/main/java/com/webgame/webgamebackend/common/utils/RedisCacheUtil.java b/src/main/java/com/webgame/webgamebackend/common/utils/RedisCacheUtil.java deleted file mode 100644 index f0deab2..0000000 --- a/src/main/java/com/webgame/webgamebackend/common/utils/RedisCacheUtil.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.webgame.webgamebackend.common.utils; - -import com.alibaba.fastjson2.JSON; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.cache.annotation.Cacheable; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.stereotype.Component; - -import java.util.concurrent.TimeUnit; - -/** - * Redis缓存工具类 - */ -@Slf4j -@Component -@RequiredArgsConstructor -public class RedisCacheUtil { - /** - * Redis缓存前缀 - */ - private final static String CACHE_KEY_PREFIX = "xzg:"; - - /** - * Redis操作类 - */ - private final RedisTemplate redisTemplate; - - /** - * 将值加入缓存 - * - * @param k 键 - * @param v 值 - * - * @return 是否成功 - */ - public Boolean cacheValue(String k, Object v) { - return cacheValue(k.startsWith(":") ? k.substring(1) : k, v, -1); - } - - /** - * 将值加入缓存,并添加过期时间。 - * - * @param k 键 - * @param v 值 - * @param expireTime 过期时间(毫秒) - * - * @return 是否成功 - */ - public Boolean cacheValue(String k, Object v, long expireTime) { - return cacheValue(k.startsWith(":") ? k.substring(1) : k, v, expireTime, TimeUnit.MILLISECONDS); - } - - /** - * 将值加入缓存,并添加过期时间。 - * - * @param k 键 - * @param v 值 - * @param expireTime 过期时间 - * @param expireUnit 过期时间单位 - * - * @return 是否成功 - */ - public Boolean cacheValue(String k, Object v, long expireTime, TimeUnit expireUnit) { - if (k.startsWith(":")) k = k.substring(1); - var key = CACHE_KEY_PREFIX + k; - - var json = ""; - try { - json = JSON.toJSONString(v); - } catch (Exception e) { - log.error("写入缓存失败, 键: {}, 原因: {}", key, e.getMessage(), e); - return false; - } - - try { - var valueOps = redisTemplate.opsForValue(); - valueOps.set(key, json); - - if (expireTime > 0) redisTemplate.expire(key, expireTime, expireUnit); - - return true; - } catch (Exception e) { - log.error("写入缓存失败, 键: {}, 值: {}, 原因: {}", key, json, e.getMessage(), e); - } - return false; - } - - /** - * 将值加入缓存,并添加过期时间 - * - * @param prefix 键组前缀 - * @param k 键 - * @param v 值 - * @param expireTime 过期时间(毫秒) - * - * @return 是否成功 - */ - public Boolean cacheValue(String prefix, String k, Object v, long expireTime) { - if (!prefix.endsWith(":")) prefix = prefix + ":"; - if (k.startsWith(":")) k = k.substring(1); - return cacheValue(prefix + k, v, expireTime); - } - - /** - * 将值加入缓存,并添加过期时间。 - * - * @param prefix 键组前缀 - * @param k 键 - * @param v 值 - * @param expireTime 过期时间(毫秒) - * - * @return 是否成功 - */ - public Boolean cacheValue(String prefix, Long k, Object v, long expireTime) { - if (prefix.startsWith(":")) prefix = prefix.substring(1); - if (!prefix.endsWith(":")) prefix = prefix + ":"; - return cacheValue(prefix + k, v, expireTime); - } - - /** - * 查询缓存 - * - * @param k 键 - * @param cls 序列化类型 - * @param expireTime 查询后更新过期时间(毫秒) - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String k, Class cls, long expireTime) { - return getCache(k.startsWith(":") ? k.substring(1) : k, cls, expireTime, TimeUnit.MILLISECONDS); - } - - /** - * 查询缓存 - * - * @param k 键 - * @param cls 序列化类型 - * @param expireTime 查询后更新过期时间 - * @param expireUnit 时间单位 - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String k, Class cls, long expireTime, TimeUnit expireUnit) { - if (k.startsWith(":")) k = k.substring(1); - var key = CACHE_KEY_PREFIX + k; - try { - // 由于 ValueOperations 的 getAndExpire 查询命令 GETEX - // 在 Redis 6.2 以下版本不支持, 由于可能服务器环境使用 WindowsServer系统, - // 安装的Redis版本小于6.2版本,所以这里使用 get + expire。 - var valueOps = redisTemplate.opsForValue(); - - // 查询缓存 - var json = valueOps.get(key); - if (json == null) return null; - - // 更新过期时间 - redisTemplate.expire(key, expireTime, expireUnit); - - // 返回结果 - return JSON.to(cls, json); - } catch (Exception e) { - log.error("查询缓存失败, 键: {}", key, e); - } - return null; - } - - /** - * 查询缓存 - * - * @param prefix 键组前缀 - * @param k 键 - * @param cls 序列化类型 - * @param expireTime 查询后更新过期时间(毫秒) - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String prefix, String k, Class cls, long expireTime) { - if (prefix.startsWith(":")) prefix = prefix.substring(1); - if (!prefix.endsWith(":")) prefix = prefix + ":"; - if (k.startsWith(":")) k = k.substring(1); - return getCache(prefix + k, cls, expireTime, TimeUnit.MILLISECONDS); - } - - /** - * 查询缓存 - * - * @param prefix 键组前缀 - * @param k 键 - * @param cls 序列化类型 - * @param expireTime 查询后更新过期时间(毫秒) - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String prefix, Long k, Class cls, long expireTime) { - if (prefix.startsWith(":")) prefix = prefix.substring(1); - if (!prefix.endsWith(":")) prefix = prefix + ":"; - return getCache(prefix + k, cls, expireTime, TimeUnit.MILLISECONDS); - } - - /** - * 查询缓存 - * - * @param k 键 - * @param cls 序列化类型 - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String k, Class cls) { - return getCache(k.startsWith(":") ? k.substring(1) : k, cls, false); - } - - /** - * 查询缓存 - * - * @param k 键 - * @param cls 序列化类型 - * @param remove 查询后是否移除 - * @param 序列化类型 - * - * @return 查询结果 - */ - public T getCache(String k, Class cls, Boolean remove) { - if (k.startsWith(":")) k = k.substring(1); - var key = CACHE_KEY_PREFIX + k; - try { - var valueOps = redisTemplate.opsForValue(); - var json = remove ? valueOps.getAndDelete(key) : valueOps.get(key); - if (json == null) return null; - - return JSON.to(cls, json); - } catch (Exception e) { - log.error("查询缓存失败, 键: {}", key, e); - } - return null; - } - - /** - * 移除缓存 - * - * @param prefix 键组前缀 - * @param k 键 - * - * @return 是否成功 - */ - public Boolean removeCache(String prefix, Long k) { - if (prefix.startsWith(":")) prefix = prefix.substring(1); - if (!prefix.endsWith(":")) prefix = prefix + ":"; - return removeCache(prefix + k); - } - - /** - * 移除缓存 - * - * @param k 键 - * - * @return 是否成功 - */ - public Boolean removeCache(String k) { - if (k.startsWith(":")) k = k.substring(1); - var key = CACHE_KEY_PREFIX + k; - try { - if (key.endsWith(":*")) { - var keys = redisTemplate.keys(key); - if (!keys.isEmpty()) - redisTemplate.delete(keys); - return true; - } else return redisTemplate.delete(key); - } catch (Exception e) { - log.error("移除缓存失败, 键: {}", key, e); - } - return false; - } - - /** - * 移除缓存 - * - * @param prefix 键组前缀 - * @param k 键 - * - * @return 是否成功 - */ - public Boolean removeCache(String prefix, String k) { - if (prefix.startsWith(":")) prefix = prefix.substring(1); - if (!prefix.endsWith(":")) prefix = prefix + ":"; - if (k.startsWith(":")) k = k.substring(1); - return removeCache(prefix + k); - } -} diff --git a/src/main/java/com/webgame/webgamebackend/common/utils/RedisMqUtil.java b/src/main/java/com/webgame/webgamebackend/common/utils/RedisMqUtil.java deleted file mode 100644 index ce654b8..0000000 --- a/src/main/java/com/webgame/webgamebackend/common/utils/RedisMqUtil.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.webgame.webgamebackend.common.utils; - -import com.alibaba.fastjson2.JSON; -import io.micrometer.common.util.StringUtils; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.connection.MessageListener; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.data.redis.listener.PatternTopic; -import org.springframework.data.redis.listener.RedisMessageListenerContainer; -import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; -import org.springframework.stereotype.Component; - -import java.util.function.Consumer; - -/** - * Redis消息队列工具类 - * @author xzg - */ -@Slf4j -@Component -@RequiredArgsConstructor -public class RedisMqUtil { - private final RedisTemplate redisTemplate; - private final RedisMessageListenerContainer redisMessageListenerContainer; - - public void pub(String channel, Object message) { - try { - if (StringUtils.isBlank(channel)) { - log.warn("[REDIS消息队列] 发布信息失败: 通道名称为 null"); - return; - } - if (message == null) { - log.warn("[REDIS消息队列] 发布信息至通道({})失败: 信息体为 null", channel); - return; - } - - // 信息体转JSON - var json = ""; - try { - json = JSON.toJSONString(message); - } catch (Exception e) { - log.warn("[REDIS消息队列] 发布信息至通道({})异常: 信息实体无法正确的序列化为JSON字符串, {}", channel, e.getMessage(), e); - return; - } - - redisTemplate.convertAndSend(channel, json); - } catch (Exception e) { - log.warn("[REDIS消息队列] 发布信息至通道({})异常: {}", channel, e.getMessage(), e); - } - } - - public void sub(String channel, Class clazz, Consumer callback) { - if (StringUtils.isBlank(channel)) { - log.warn("[REDIS消息队列] 订阅通道失败, 通道名称不可为空"); - return; - } - if (callback == null) { - log.warn("[REDIS消息队列] 订阅通道({})失败, 回调方法不可为空", channel); - return; - } - - try { - var adapter = new MessageListenerAdapter((MessageListener) (message, pattern) -> { - var body = message.getBody(); - var channelName = new String(message.getChannel()); - - T dto; - try { - dto = JSON.parseObject(new String(body), clazz); - } catch (Exception e) { - log.error("[REDIS消息队列] 消费通道({})信息实体类型转换处理异常: {}, 信息: {}", channelName, e.getMessage(), body, e); - return; - } - try { - callback.accept(dto); - } catch (Exception e) { - log.error("[REDIS消息队列] 消费通道({})信息回调处理异常: {}, 信息: {}", channelName, e.getMessage(), body, e); - } - }); - - redisMessageListenerContainer.addMessageListener(adapter, new PatternTopic(channel)); - } catch (Exception e) { - log.error("[REDIS消息队列] 订阅通道({})异常: {}", channel, e.getMessage(), e); - return; - } - - log.info("[REDIS消息队列] 订阅通道({})成功", channel); - } -} diff --git a/src/main/java/com/webgame/webgamebackend/service/impl/RefreshTokenServiceImpl.java b/src/main/java/com/webgame/webgamebackend/service/impl/RefreshTokenServiceImpl.java index 5e333c8..ede8d78 100644 --- a/src/main/java/com/webgame/webgamebackend/service/impl/RefreshTokenServiceImpl.java +++ b/src/main/java/com/webgame/webgamebackend/service/impl/RefreshTokenServiceImpl.java @@ -47,6 +47,9 @@ public class RefreshTokenServiceImpl implements RefreshTokenService { @Override public String create(String userId) { + if (userId == null || userId.isBlank()) { + throw new BusinessException(ErrorCode.BAD_REQUEST, "用户ID不能为空"); + } // 先清除该用户之前的 refresh token,确保一个用户只有一个有效 token String oldToken = get(USER_KEY_PREFIX + userId); if (oldToken != null) { @@ -78,21 +81,30 @@ public class RefreshTokenServiceImpl implements RefreshTokenService { @Override public String rotate(String oldToken) { String userId = validate(oldToken); - delete(KEY_PREFIX + oldToken); + // 先删反向映射,再删正向映射: + // 若反向映射删除失败,正向映射仍存在,调用方可重试; + // 若反向已删除而正向删除失败,正向映射仍存在,重试仍可通过。 delete(USER_KEY_PREFIX + userId); + delete(KEY_PREFIX + oldToken); log.debug("旧刷新令牌已删除: userId={}", userId); return create(userId); } @Override public void revoke(String token) { - if (token != null && !token.isBlank()) { + if (token == null || token.isBlank()) { + return; + } + try { String userId = get(KEY_PREFIX + token); if (userId != null) { delete(USER_KEY_PREFIX + userId); } delete(KEY_PREFIX + token); log.debug("刷新令牌已撤销"); + } catch (BusinessException e) { + // 登出时 Redis 不可用,记录日志后放行,不影响用户登出 + log.warn("撤销刷新令牌失败(Redis 不可用),跳过清理: token={}", token, e); } } @@ -110,6 +122,9 @@ public class RefreshTokenServiceImpl implements RefreshTokenService { /** * 从 Redis 读取字符串(读取时续期) + * + * @return 值,key 不存在时返回 null + * @throws BusinessException Redis 操作失败时抛出 */ private String get(String key) { try { @@ -120,18 +135,21 @@ public class RefreshTokenServiceImpl implements RefreshTokenService { return value; } catch (Exception e) { log.error("查询缓存失败: key={}", key, e); - return null; + throw new BusinessException(ErrorCode.INTERNAL_ERROR, "刷新令牌操作失败"); } } /** * 从 Redis 删除 key + * + * @throws BusinessException Redis 操作失败时抛出 */ private void delete(String key) { try { stringRedisTemplate.delete(key); } catch (Exception e) { log.error("删除缓存失败: key={}", key, e); + throw new BusinessException(ErrorCode.INTERNAL_ERROR, "刷新令牌操作失败"); } }