【发布时间】:2021-07-04 07:21:18
【问题描述】:
我在我的 Spring Boot 应用程序中使用 Redis 作为内存数据存储,用于缓存目的。目前,我已经为需要缓存的实体实现了具有基本 CRUD 功能的 Redis 支持 [场景 1]。但突然间我发现有很多资源使用额外的 Spring Boot 缓存注释,如 @Cachable @CahceEvict 来实现 Redis [场景 2] 的缓存。我监控到,当我们开始在诸如 find(params) 之类的操作中使用这些注释时,只有第一个方法调用会转到 Redis。从第二种方法开始,Redis 不会受到攻击。所以根据我的观察,我认为,Spring boot 维护了一个单独的缓存。但我的问题是我们已经在使用 Redis 作为我们的缓存。那么停止第二次 Redis 数据存储命中并维护另一个缓存有什么好处。我的意思是 Redis 已经在 RAM 中并且它具有很强的缓存能力。为什么我们需要维护两个缓存?拥有这种机制有什么好处吗?或者只实现 Redis 就足够了?
场景 1:
public class RestController{
@GetMapping("/{id}")
public Product findProductById(@PathVariable int Id){
return dao.findProductById(id);
}
}
@Repository
public class ProductDao {
public static final String HASH_KEY = "Product";
@Autowired
private RedisTemplate template;
public Product findProductById(int id){
return (Product) template.opsForHash().get(HASH_KEY,id);
}
}
场景 2:
public class RestController{
@GetMapping("/{id}")
@Cachable(key = "#id" ,value="Product")
public Product findProductById(@PathVariable int Id){
return dao.findProductById(id);
}
}
@Repository
public class ProductDao {
public static final String HASH_KEY = "Product";
@Autowired
private RedisTemplate template;
public Product findProductById(int id){
System.out.println("called findProductById() from DB");//Here only for the first time method will be called
return (Product) template.opsForHash().get(HASH_KEY,id);
}
}
【问题讨论】:
-
假设代码直接处理缓存 - 这将要求缓存中涉及的每个方法都知道,并使用一些(希望注入的)依赖项。这是可能的,但噪音很大,可能至少有一些重复的代码。每个单元测试都需要额外的设置,这不提供商业价值(也许这样的测试没有功能价值)。注释抽象出缓存实现,因此一旦配置了缓存提供程序,您就完成了。但请考虑添加一些集成测试来验证缓存是否正常工作。
-
@Andrew S 实际上,我不确定您是否正确理解了我的问题。我的意思是认为您正在实现您的 redis 存储库(数据访问层)并且您正在调用一个示例方法调用 findById(params) ,我在视频中看到当您使用 Cachable 注释时,只有第一次数据将从实际的 redis 中检索数据存储。但是从第二次调用实际上 findById(params) 不会被触发。因为spring会将值缓存在其他地方并交出。所以我问为什么我们需要这样的机制。因为我们已经在使用 Redis 作为缓存了。
-
请查看参考资料。
标签: java spring caching redis spring-data-redis