我的代码是这样的:
爪哇:
@Autowired
private RedisTemplate<String,User> myTemplate;
@Override
public String login(String email, String password) {
User user = this.userRepository.findByEmailAndPassword(email, password);
System.out.println(user);
if (user == null) return null;
String key1 = "lic" + "$" + user.getId() + "$" + user.getRole() + "$" + user.getName() + "$" + user.getEmail();
ValueOperations<String, User> ops = this.myTemplate.opsForValue();
if (!this.myTemplate.hasKey(key1)) {
ops.set(key1, user);
}
return key1;
}
当app运行时,注入bean,就像这样:
@SpringBootApplication
public class ApplicationApp extends WebMvcConfigurerAdapter {
// @Autowired
// private RedisTemplate<String,String> template;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
RedisTemplate<String, User> redisTemplate() {
final RedisTemplate<String, User> template = new RedisTemplate<String, User>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericToStringSerializer<User>(User.class));
template.setValueSerializer(new GenericToStringSerializer<User>(User.class));
return template;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// super.addInterceptors(registry);
registry.addInterceptor(new AuthorAccess()).addPathPatterns("/api/sc/**");
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationApp.class, args);
}
}
然后,调用登录服务发现错误如下:
org.springframework.core.convert.ConverterNotFoundException:找不到能够从类型com.qycloud.oatos.license.domain.User转换为类型java.lang.String的转换器
答案 0 :(得分:3)
使用Jackson2JsonRedisSerializer而不是GenericToStringSerializer设置ValueSerializer,它应该可以工作。 GenericToStringSerializer不支持Object to String转换。
template.setValueSerializer(new Jackson2JsonRedisSerializer<User>(User.class));
答案 1 :(得分:0)
您需要通过例如注册您自己的TypeConverter
或ConversionService
的实施方式来处理User.class
。 setTypeConverter(TypeConverter converter)
。否则,GenericToStringSerializer
会尝试使用不知道您的类型的DefaultConversionService
。