Commit a5aa961e by 叶立庆

修复Redis 序列化问题

1 parent ee53bdc9
...@@ -11,6 +11,7 @@ import org.springframework.context.annotation.Bean; ...@@ -11,6 +11,7 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer;
...@@ -20,6 +21,15 @@ import org.springframework.data.redis.serializer.StringRedisSerializer; ...@@ -20,6 +21,15 @@ import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration @Configuration
public class RedisConfig { public class RedisConfig {
/**
* 纯字符串模板:用于只存「字符串 / 简单 JSON」的缓存(如权限码集合),
* 避免 {@link GenericJackson2JsonRedisSerializer} 的默认类型推断把纯数组首元素误判为类型 id。
*/
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
@Bean @Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>(); RedisTemplate<String, Object> template = new RedisTemplate<>();
......
package com.youjia.framework.security; package com.youjia.framework.security;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
...@@ -45,8 +49,17 @@ public class AuthTokenService { ...@@ -45,8 +49,17 @@ public class AuthTokenService {
private static final String KEY_LOCK = PREFIX + "lock:"; private static final String KEY_LOCK = PREFIX + "lock:";
private final RedisTemplate<String, Object> redisTemplate; private final RedisTemplate<String, Object> redisTemplate;
private final StringRedisTemplate stringRedisTemplate;
private final AuthProperties authProperties; private final AuthProperties authProperties;
/**
* 权限码缓存专用序列化器:<b>不带默认类型推断</b>,只做 {@code List<String>} ↔ JSON 数组的纯文本转换。
* 避免权限码这类简单集合被 {@code GenericJackson2JsonRedisSerializer} 的 @class 类型信息机制误处理。
*/
private final ObjectMapper permObjectMapper = new ObjectMapper().registerModule(new JavaTimeModule());
private static final TypeReference<List<String>> PERM_TYPE_REF = new TypeReference<List<String>>() {
};
/* ------------------------------------------------------------------ 会话 */ /* ------------------------------------------------------------------ 会话 */
/** 建立会话,返回令牌 */ /** 建立会话,返回令牌 */
...@@ -69,10 +82,17 @@ public class AuthTokenService { ...@@ -69,10 +82,17 @@ public class AuthTokenService {
if (token == null || token.isBlank()) { if (token == null || token.isBlank()) {
return null; return null;
} }
Object value = redisTemplate.opsForValue().get(KEY_TOKEN + token); Object value;
try {
value = redisTemplate.opsForValue().get(KEY_TOKEN + token);
} catch (Exception e) {
// 会话条目损坏(如旧版本写入格式不兼容)时,按未登录处理,不让异常冒泡成 500
log.warn("会话反序列化失败,已按未登录处理:{}", token, e);
return null;
}
if (!(value instanceof LoginUser loginUser)) { if (!(value instanceof LoginUser loginUser)) {
if (value != null) { if (value != null) {
log.warn("会话反序列化失败,已按未登录处理:{}", token); log.warn("会话类型不匹配,已按未登录处理:{}", token);
} }
return null; return null;
} }
...@@ -161,11 +181,22 @@ public class AuthTokenService { ...@@ -161,11 +181,22 @@ public class AuthTokenService {
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public List<String> getPermCodes(Long userId, Supplier<List<String>> loader) { public List<String> getPermCodes(Long userId, Supplier<List<String>> loader) {
Object cached = redisTemplate.opsForValue().get(KEY_PERM + userId); String raw = null;
if (cached instanceof List<?> list) { try {
List<String> codes = (List<String>) list; raw = stringRedisTemplate.opsForValue().get(KEY_PERM + userId);
if (!codes.isEmpty()) { } catch (Exception e) {
return codes; log.warn("读取权限缓存失败,按未命中处理并重新加载:userId={}", userId, e);
}
if (raw != null && !raw.isBlank()) {
try {
List<String> codes = permObjectMapper.readValue(raw, PERM_TYPE_REF);
if (codes != null && !codes.isEmpty()) {
return codes;
}
} catch (Exception e) {
// 旧版本/其他应用残留的不兼容格式(如缺 @class 的纯数组)会被默认类型推断误判为类名,
// 这里捕获后按未命中处理,由下方回源重建,避免登录或鉴权直接 500。
log.warn("权限缓存反序列化失败(格式不兼容),按未命中处理并重建:userId={}", userId, e);
} }
} }
List<String> loaded = loader.get(); List<String> loaded = loader.get();
...@@ -174,14 +205,19 @@ public class AuthTokenService { ...@@ -174,14 +205,19 @@ public class AuthTokenService {
Duration ttl = Duration.ofSeconds(codes.isEmpty() Duration ttl = Duration.ofSeconds(codes.isEmpty()
? Math.max(60, authProperties.getPermCacheSeconds() / 2) ? Math.max(60, authProperties.getPermCacheSeconds() / 2)
: authProperties.getPermCacheSeconds()); : authProperties.getPermCacheSeconds());
redisTemplate.opsForValue().set(KEY_PERM + userId, codes, ttl); try {
stringRedisTemplate.opsForValue().set(KEY_PERM + userId,
permObjectMapper.writeValueAsString(codes), ttl);
} catch (Exception e) {
log.warn("回写权限缓存失败(不影响本次请求):userId={}", userId, e);
}
return codes; return codes;
} }
/** 失效单个用户的权限缓存,用户下次请求时按新权限重新加载 */ /** 失效单个用户的权限缓存,用户下次请求时按新权限重新加载 */
public void evictPermCache(Long userId) { public void evictPermCache(Long userId) {
if (userId != null) { if (userId != null) {
redisTemplate.delete(KEY_PERM + userId); stringRedisTemplate.delete(KEY_PERM + userId);
} }
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!