Spring boot cache的Simple Cache更新数据后获取的缓存数据为null问题
问题代码如下:
@Cacheable(key = "#playerId")
public Player getPlayer(Long playerId) {
return playerRepository.getOne(playerId);
}
@CachePut(key = "#player.playerId")
public void updateOrInsertPlayer(Player player) {
return playerRepository.save(player);
}
@CacheEvict(key = "#playerId")
public void remove(Long id) {
playerRepository.deleteById(id);
}
执行操作:
1、调用getPlayer获取了数据,数据进入缓存;
2、调用updateOrInsertPlayer更新数据;
3、再次调用getPlayer获取数据,数据却为null;
问题原因:
updateOrInsertPlayer方法没有返回值,因为调用完该方法会把缓存数据更新为null。
解决方法:
updateOrInsertPlayer方法添加缓存返回。代码如下:
@CachePut(key = "#player.playerId")
public Player updateOrInsertPlayer(Player player) {
return playerRepository.save(player);
}
本文探讨了SpringBoot中使用SimpleCache时,更新数据后获取的缓存数据为null的问题。详细分析了@CachePut注解方法未正确返回更新后的实体,导致缓存更新失败的情况,并提供了修改方法以确保缓存更新机制正常工作。
1382

被折叠的 条评论
为什么被折叠?



