当使用@Cacheable和@CachePut注解存数据到redis中时如果使用spring默认的redis key序列化方式时,使用redisTemplate取数据为null
@CacheConfig(cacheNames = "users") 存入redis users目录下取数据时的key为users::username public interface UserRepository extends JpaRepository<User, Long> { @Query("from User u where u.username=:username") User findUser(@Param("username") String username); @Cacheable(key = "#p0") //使用第一个参数作为key User findUserByUsername(String username); @CachePut(key = "#p0.username") User save(User user); }
不配置redisTemplate的效果:
@Test public void before() { userRepository.save(new User("AAA", 10)); System.out.println("直接从redis取数据:" + redisTemplate.opsForValue().get("users::AAA")); }
//Hibernate: insert into user (age, username) values (?, ?)
//直接从redis取数据:null
配置redis key的序列化方式
@Configuration public class RedisConfig { @Bean public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); GenericToStringSerializer<String> stringGenericToStringSerializer = new GenericToStringSerializer<>(String.class); redisTemplate.setKeySerializer(stringGenericToStringSerializer); redisTemplate.setHashKeySerializer(stringGenericToStringSerializer); redisTemplate.setStringSerializer(stringGenericToStringSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
配置完后打印结果
Hibernate: insert into user (age, username) values (?, ?)
直接从redis取数据:com.cw.study.domain.User@41cf4272
说明默认的redisTemplate序列化key的方式和@Cacheable、@CachePut序列化key的方式不同
标签:username,Cacheable,redis,CachePut,User,key,redisTemplate From: https://www.cnblogs.com/wscw/p/17301369.html