如果仅用于简单缓存,Redis 缓存是否比 Spring 缓存有优势?

Does Redis cache have advantage over Spring cache if used only for simple cache?

我是缓存事物的新手,正在为我的 spring 启动应用学习一些不同的解决方案。我正在查看 Spring 缓存,它比我看到的 redis 缓存更简单的缓存机制(这正是我所寻找的)。而且像"spring+redis cache"这样的资源非常多。当我查看简单用法时,我看不出有什么区别。甚至注释都是相同的(Cacheable、CacheEvict、CachePut 等),除了额外的 redis 配置和 redis docker 容器等之外,我看不出用法上的差异......并且 none 这些 spring+redis cache文章说了just spring cache和spring+redis cache有什么区别

redis 缓存相对于 spring 缓存有什么优势?或者你能告诉一个简单的用例,我肯定需要使用 redis 缓存,而我无法使用 spring 缓存来实现它吗?

从实现的角度来看,没有“Spring 缓存”这样的东西。但是,有 Spring's Cache Abstraction 提供通用缓存设施,它起源于核心 Spring 框架。

缓存抽象 基本上是 Adapter enabling different caching providers to be plugged into the framework and used generically for caching purposes. Caching can be applied in any tier of your Spring [Boot] application, for example, in the data access layer, or service layer, and so on. Caching can even be applied in multiple tiers simultaneously. Caching is, after all, a cross-cutting concern, and is, not coincidently, implemented with Spring AOP

抽象提供了一个外观,包括 API along with Annotations for the most common caching operations (for example: Cache.put(key, value), Cache.get(key), Cache.evict(key),等等)。这些缓存操作是相当标准的,并且在大多数缓存提供程序实现中都很常见(例如 Redis、Hazelcast、Apache Geode,甚至 Java 的 MapConcurrentMap 实现;缓存实际上是 Map-like数据结构)。

每个 缓存提供程序 必须提供 Cache and CacheManager interfaces defined by Spring's Cache Abstraction in order to be able to be plugged into the framework for caching purposes. In this way, every caching provider can be treated generically using Spring's caching API (or Annotations, and even the JCache annotations) 的实现,以便您 1) 不绑定到任何特定的缓存提供程序,然后 2) 允许您在您的应用程序用例或需求发生变化时交换缓存提供程序。

到目前为止有意义吗?

Out-of-the-box、Spring(启动)配置 ConcurrentMap 缓存实现(参见 here, then here (source) and finally, here followed by this)作为缓存提供程序在没有其他缓存提供程序时插入框架(例如 Redis) 存在于应用程序类路径中。

但是,ConcurrentMap 缓存实现和 Redis 提供程序实现之间存在很大差异。后者插入一个 Redis 客户端,该客户端可以远程连接到 Redis 服务器集群。这意味着,从本质上讲,您可以拥有一个“分布式”缓存,其中负载可以均匀分布,假设您正确配置了缓存提供程序,如 Redis。

并非所有缓存提供程序都是平等的。有些提供许多附加服务,有些甚至可以作为整个应用程序的记录系统 (SoR),甚至可能最终取代 RDBMS。

即使大多数缓存提供程序都能够进行复杂的逐出(LRU、LFU)和过期,Spring 的缓存抽象 does not specify这些能力。这留给您根据您选择的缓存提供程序来决定和配置。

Apache Geode 和 Hazelcast 等完全分布式缓存提供程序也提供内存管理功能(毕竟 keys/values 存储 in-memory)。它们甚至可以配置为持久性(因此 SoR UC),支持不同的拓扑结构:client/server、WAN(multi-site)、嵌入式,并支持不同的缓存模式(Cache-Aside、内联缓存、近缓存等)以及不同的缓存 UC(例如(HTTP)会话状态缓存)。

免责声明:我是 Apache Geode 产品 Spring 背后的 Spring 数据工程师,因此我将给您留下 chapter 我致力于在 Spring Boot for Apache Geode 参考指南。

这个post应该能让你有足够的时间咀嚼一段时间。

如有其他问题,请在评论中提问。