问题影响

这种序列化后的 key 会导致:

  1. 登出时无法匹配 key:代码中用 token:FuHan 去删除,但 Redis 中实际存储的是序列化后的 \xac\xed\x00\x05t\x00\x0btoken:FuHan,因此删除操作会失败。
  2. 可读性差:无法通过 redis-cli 直接识别 key 的含义。

解决方法:修改 Redis 序列化方式

需要将 Redis 的 key 序列化器 改为 StringRedisSerializer(纯字符串序列化),确保 key 以明文存储。

步骤 1:配置 RedisTemplate 的序列化器

在 Spring Boot 项目中,添加如下配置类:

java

运行

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // 设置 key 的序列化器为 StringRedisSerializer
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        
        // 值的序列化器可根据需求选择(如 Jackson2JsonRedisSerializer)
        // template.setValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
        
        return template;
    }
}
步骤 2:重启服务并重新登录

修改配置后,重启 Spring Boot 应用,然后重新执行登录操作。此时 Redis 中存储的 key 会变成明文(如 token:FuHantoken:refresh:FuHan)。

验证结果

再次执行 redis-cli 命令:

bash

redis-cli
> KEYS *
1) "token:FuHan"
2) "token:refresh:FuHan"

此时 key 已变为明文,登出时就能通过 token:用户名 正确匹配并删除 Redis 中的 Token 了。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐