在使用SpringBoot Redis里的scan方法扫描匹配的keys时出现了诡异的乱码前缀,类似如下截图: 字符串如下:
��t�online-token-eyJhbGciOiJIUzUxMiJ9.eyJqdGkiOiIwOWM1MDVkM2ZlMjE0OGVmYTk5MmQwNjhlOGVkYzNmMCIsInVzZXIiOiJhZG1pbiIsInN1YiI6ImFkbWluIn0.fB8T1s1tK6Z4SM9nGu1Dot9EXmdOoxcDaBIhcMur00RQy5PZk0fADRSf0gqFWGhjhrfEXFGaE1kpuwQ6qQi_kw
scan的实现源码如下:
public List<String> matchScan(String pattern) {
List<String> keys = redisTemplate.execute((RedisCallback<List<String>>) connection -> {
List<String> keysTmp = new ArrayList<>();
Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(pattern).count(10000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
return keysTmp;
});
return keys;
}
原因分析
刚开始的时候找了很久没有找到原因,最后在stackoverflow上找到了提示: https://stackoverflow.com/questions/55967558/spring-data-redis-hash-keys-with-weird-prefixes-and-hscan-not-returning-resul
原来是序列化问题导致,默认使用了JDK的序列化方法。
解决方案
采用Redis自带的序列化方法。初始化redisTemplate时,进行设置,代码如下:
public RedisUtils(RedisTemplate<Object, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
this.redisTemplate.setHashKeySerializer(new StringRedisSerializer());
this.redisTemplate.setKeySerializer(new StringRedisSerializer());
this.redisTemplate.setStringSerializer(new StringRedisSerializer());
}
重新构建运行后,正常了。
|