简而言之:
对于 RedisTemplate来说, k、v 都可以是任何类型,
对于 StringRedisTemplate 来说, k、v 都必须是 String类型,包括 hash、set。 而且key 不能使用 对象,因为不会调用 toString(), 否则引起 cast 异常
传给 RedisTemplate、StringRedisTemplate 相同的key ,但是对于redis 来说, 是不同的, 如下,同一个key 123,实际的key 完全不同:
127.0.0.1:6379> keys *
1) "xacxedx00x05tx00x03123"
2) "123"
127.0.0.1:6379> get 123
"123 Sun Jan 31 15:42:33 CST 2021"
127.0.0.1:6379> get "xacxedx00x05tx00x03123"
"xacxedx00x05srx00x11com.forezp.PersonxffQxfe xb3xe0x10xb6x02x00x03Lx00 firstnametx00x12Ljava/lang/String;Lx00x02idqx00~x00x01Lx00lastnameqx00~x00x01xptx00x03123ptx00x04 Lea"
又比如:
@Autowired
StringRedisTemplate stringRedisTemplate; // t1
@Autowired
RedisTemplate<String, String> redisTemplate1; // t2
@Autowired
RedisTemplate redisTemplate; // t3
@Autowired
RedisTemplate<String, Object> redisTemplate2; // t4
@Autowired(required = false)
RedisTemplate<Object, Object> redisTemplate3; // t5
调试发现 t1 就是 t2, t3 就是 t4, t5 无法注入, 为null
为什么呢?
因为
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
redisTemplate.afterPropertiesSet();
setSerializer(redisTemplate);
System.out.println("redisTemplate = " + redisTemplate);
return redisTemplate;
}
private void setSerializer(RedisTemplate<String, Object> template) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(jackson2JsonRedisSerializer);
}