引入依赖
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
问题描述
如下面 箭头所示,对于spring-session-data-redis存储了session的数据时,会出现乱码。
这些乱码不应该出现,看起来不优雅,并且这些乱码占用空间,存储较多数据的时候,会占用大量内存。
问题出现原因
spring-session-data-redis默认使用原生的JdkSerializationRedisSerializer。
翻看源码RedisIndexedSessionRepository查看,这就是出现乱码的原因,存储格式不符合。
问题解决方案
查看官方文档:官方文档
问题解决代码
使用FastJsonRedisSerializer
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
// 使用 FastJsonRedisSerializer 来序列化和反序列化redis 的 value的值
FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
ParserConfig.getGlobalInstance().addAccept("com.muzz");
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
serializer.setFastJsonConfig(fastJsonConfig);
return serializer;
}
除了使用上面的序列化器之前,官方还推荐GenericFastJsonRedisSerializer序列化
@Bean
public RedisSerializer<Object> springSessionDefaultRedisSerializer() {
// 使用 FastJsonRedisSerializer 来序列化和反序列化 redis 的 value的值
// FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);
// ParserConfig.getGlobalInstance().addAccept("com.muzz.");
// ParserConfig.getGlobalInstance().addAccept("org.springframework.");
// ParserConfig.getGlobalInstance().addAccept("org.springframework.security.core.context.");
// FastJsonConfig fastJsonConfig = new FastJsonConfig();
// fastJsonConfig.setCharset(StandardCharsets.UTF_8);
// serializer.setFastJsonConfig(fastJsonConfig);
// return serializer;
return new GenericFastJsonRedisSerializer();
}
之所以使用这个之外,是因为我在使用springboot security的时候,发现了一个错误。
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'authentication' cannot be found on object of type 'com.alibaba.fastjson.JSONObject' - maybe not public or not valid?
at org.springframework.expression.spel.ast.PropertyOrFieldReference.readProperty(PropertyOrFieldReference.java:217) ~[spring-expression-5.3.1.jar:5.3.1]
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:104) ~[spring-expression-5.3.1.jar:5.3.1]
at org.springframework.expression.spel.ast.PropertyOrFieldReference.getValueInternal(PropertyOrFieldReference.java:91) ~[spring-expression-5.3.1.jar:5.3.1]
at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:55) ~[spring-expression-5.3.1.jar:5.3.1]
....
在使用了 GenericFastJsonRedisSerializer这个序列化器之后,就可以解决上述问题。
效果显示
对比上面的问题显示,可以发现乱码解决了
总结
多看文档,文档藏金子。