经过测试,spring cache中每种键值对之间并不互通,即在一种键值对下更新了(使用put),只会对用该种键查询时的结果产生影响。如下:
@Test
void contextLoads() {
User user1 = userCache.getUser("alw008");
User user2 = userCache.getUser(3L);
user2.setAccountNonExpired(false);
userCache.putUser(user2);
System.out.println(userCache.getUser(3L).getAccountNonExpired());
}
当用户缓存提供了两种键值对时,如果put方法没有申明相应的键值对,将产生脏读问题。
解决方案:
个人倾向于在put方法的注释前使用@Caching注解,将所有重载的键类型用@CachePut注解进去,如:
@Cacheable(key = "#username")
public User getUser(String username) {
log.info("Caching user: " + username + "...");
UserExample userExample = new UserExample();
userExample.createCriteria().andUsernameEqualTo(username);
return userMapper.selectByExample(userExample).get(0);
}
@Cacheable(key = "#id")
public User getUser(Long id) {
log.info("Caching user with id: " + id + "...");
return userMapper.selectByPrimaryKey(id);
}
@Caching(put = {
@CachePut(key = "#user.id"),
@CachePut(key = "#user.username")
})
public User putUser(User user) {
log.info("Writing through User cache with <userId> : <" + user.getId() + ">...");
userMapper.updateByPrimaryKey(user);
return user;
}
类似的,evict也需要类似操作。
Spring Cache有多种查询方式(键值对)时,需要注意的一个问题
原文:https://www.cnblogs.com/eddywei/p/14133974.html