英文:
What is the default cache strategy when using Redis with spring or spring boot?
问题
有各种缓存策略,如:Cache Aside,Read Through,Write Through,Write Behind,Write Around。
当使用spring-boot-starter-data-redis
依赖与Spring Boot一起使用Redis时,默认的缓存策略是什么。如何更改这个策略。如有任何参考资料将不胜感激。
英文:
There are various cache strategies like: Cache Aside, Read Through, Write Through, Write Behind, Write Around.
When Redis is used with spring boot using spring-boot-starter-data-redis
dependency, what is the default Cache Strategy. And how can this be changed. Any reference will be greatly appreciated.
答案1
得分: 3
默认情况下,您会获得缓存旁路功能,我们在 Spring Boot 应用程序中的缓存使用看起来类似于这样:
@Cacheable(cacheNames = "someCache")
public String cacheThis(String id){
return "this Is it";
}
在大多数情况下,我们在 Spring Boot 应用程序中缓存 JPA 或其他数据库查询的结果。在这种情况下,我们在查询方法上添加 Cacheable
注解,这给了我们缓存旁路功能。
应用程序可以通过实现缓存旁路策略来模拟读取穿越缓存的功能。该策略根据需要将数据加载到缓存中。
参考:https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside
但并不是在所有问题场景下使用缓存旁路模式都是解决方案,根据您的用例,您可能需要更改缓存策略。更改缓存策略并不是一件直接的事情,除了 Spring 框架中我们知道的一些注解之外,您可能需要更新应用程序代码以使用其他缓存策略。
以下是一些已知的注解:
- Cacheable
- CacheEvict
- CachePut
您需要更新应用程序代码以使用其他缓存策略,虽然您可以使用这些注解构建任何缓存策略。如果您不想使用这些注解,您可以与实际的缓存对象交互,随时可以调用缓存方法来修改缓存。
例如:
Cache myCache = cacheManager.getCache("myCache");
一旦您有了缓存对象,您可以调用所有相关方法,由于底层缓存的限制,一些方法可能无法按预期工作。
英文:
By default, you get cache aside, our cache usage in the Spring boot app looks something similar to this
@Cacheable(cacheNames = "someCache")
public String cacheThis(String id){
return "this Is it";
}
In most of the scenarios in the spring boot app, we cache the result of JPA or other DB queries. In such cases, we add Cacheable
on the query method, which gives us cache aside feature.
> An application can emulate the functionality of read-through caching
> by implementing the cache-aside strategy. This strategy loads data
> into the cache on demand.
>
Ref: https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside
Using cache aside pattern is not the always solution to a problem, depending on your use case you might have to change the caching strategy. Changing caching strategy is not straight forward except some annotations we know from the Spring framework like
- Cacheable
- CacheEvict
- CachePut
You need to update your application code to use other caching strategies, though you can build any caching strategy using these annotations. If you don't like to use these annotations then play with the actual cache object, at any time you can call Cache methods to modify the cache.
eg
Cache myCache = cacheManager.getCache("myCache");
Once you have a cache object, you can call all relevant methods, some methods may not work as expected due to the limitation of the underlying cache.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论