Spring 的 Redis缓存注解
Eijux(讨论 | 贡献)2021年11月7日 (日) 21:37的版本 (建立内容为“category:Redis == 关于 == 前面讲的 Redis 缓存实现都是基于 Java 代码实现的。在 Spring 中,通过合理的添加缓存注解,也能…”的新页面)
关于
前面讲的 Redis 缓存实现都是基于 Java 代码实现的。在 Spring 中,通过合理的添加缓存注解,也能实现和前面示例程序中一样的缓存功能。
为了方便地提供缓存能力,Spring 提供了一组缓存注解。但是,这组注解不仅仅是针对 Redis,它本质上并不是一种具体的缓存实现方案(例如:Redis、EHCache等),而是对缓存使用的统一抽象。
- 通过这组缓存注解,然后加上与具体缓存相匹配的 Spring 配置,不用编码就可以快速达到缓存的效果。
配置 spring-redis.xml
在使用 Spring 缓存注解前,首先需要配置文件中启用 Spring 对基于注解的 Cache 的支持:
- 在“spring-redis.xml”中,加上“<cache:annotationdriven/>”配置项。
- 还需要配置一个名为 CacheManager 的缓存管理器 Spring Bean。
spring-redis.xml 增加的配置项,具体如下:
<!-- 省略其他的spring-redis.xml配置,具体参见源代码 --> <!-- (redis 数据源、Spring-redis 连接池管理工厂、redis template definition、将 redisTemplate 封装成通用服务,等) --> <!-- . . . --> <!--启用缓存注解功能,这个是必须的,否则注解不会生效 --> <cache:annotation-driven/> <!--自定义 redis 工具类,在需要缓存的地方注入此类 --> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg ref="redisTemplate"/> <constructor-arg name="cacheNames"> <set> <!--声明 userCache--> <value>userCache</value> </set> </constructor-arg> </bean>
“<cache:annotation-driven />”有一个“cache-manager”属性,用来指定所需要用到的缓存管理器(CacheManager)的 Spring Bean 的名称。 【如果不设置,则默认使用 CacheManager。】 【】 这个 Bean,要求实现 CacheManager 接口: CacheManager 接口是 Spring 定义的一个用来管理 Cache 缓存的通用接口。对应于不同的缓存,需要使用不同的 CacheManager 实现。
- Spring 自身已经提供了一种 CacheManager 的实现,是基于 Java API 的 ConcurrentMap 简单的内存 Key-Value 缓存实现。
- 但是,这里需要使用的缓存是 Redis,所以使用 spring-data-redis 包中的 RedisCacheManager 实现。