问题背景
a服务写入redis的数据,b服务读出后,value值多了个双引号。
如 “string” 获取到的是 ““string””
问题原因
a服务添加了一个redistemplate bean配置:
@configuration
public class redistemplateconfig {
@bean(name = "redistemplate")
public redistemplate setredistemplate(redisconnectionfactory redisconnectionfactory, redisproperties redisproperties) {
stringredistemplate template = new stringredistemplate(redisconnectionfactory);
jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
redisproperties.setpassword(secretkeyclient.getpassword(
system.getproperty("datakeeper.application.redis.community.key_name")));
objectmapper om = new objectmapper();
om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
jackson2jsonredisserializer.setobjectmapper(om);
template.setvalueserializer(jackson2jsonredisserializer);
template.sethashvalueserializer(jackson2jsonredisserializer);
template.afterpropertiesset();
return template;
}
}我们可以看到valueserializer用的是jackson2jsonredisserializer。
使用的时候通过@resource注解引入:
@resource
private redistemplate<string, string> redistemplate;@resource默认就是通过beanname注入的,所以此时注入的redistemplate就是我们上面配置的。
在b服务中:
也配置了这样一个redistemplate:
@configuration
public class redistemplateconfig {
@bean(name = "redistemplate")
public redistemplate setredistemplate(redisconnectionfactory redisconnectionfactory, redisproperties redisproperties) {
stringredistemplate template = new stringredistemplate(redisconnectionfactory);
jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class);
redisproperties.setpassword(secretkeyclient.getpassword(
system.getproperty("datakeeper.application.redis.community.key_name")));
objectmapper om = new objectmapper();
om.setvisibility(propertyaccessor.all, jsonautodetect.visibility.any);
om.enabledefaulttyping(objectmapper.defaulttyping.non_final);
jackson2jsonredisserializer.setobjectmapper(om);
template.setvalueserializer(jackson2jsonredisserializer);
template.sethashvalueserializer(jackson2jsonredisserializer);
template.afterpropertiesset();
return template;
}
}配置和a服务一模一样。
但是,在使用redistemplate时采用的@autowired注解:
@autowired
private redistemplate<string, string> redistemplate;我们知道@autowired注解默认是按照beanclass即beantype进行注入的,此时注入的redistemplate却不是我们上面配置的,而是springboot自动配置的。
在redisautoconfiguration中:
@bean
@conditionalonmissingbean(name = "redistemplate")
public redistemplate<object, object> redistemplate(
redisconnectionfactory redisconnectionfactory) throws unknownhostexception {
redistemplate<object, object> template = new redistemplate<>();
template.setconnectionfactory(redisconnectionfactory);
return template;
}我们看到,我们配置的与springboot默认的redistemplate不相同。
通过打断点进行对比:
springboot默认的:

我们自己定义的:

可以看到,在valueserializer上,一个是stringredisserializer,一个是jackson2jsonredisserializer。
所以,在序列化与反序列化的方式不同时,产生这种乱码,奇怪的双引号问题也就可以解释了。
解决方案
将序列化反序列化方式改成一致。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论