Redis 缓存 + Spring 的集成示例

简介:

整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 Spring MVC、IOC、MyBatis ORM 三者的整合以及声明式事务处理。现在我们需要把缓存也整合进来,缓存我们选用的是 Redis,本文将在该文示例基础上介绍 Redis 缓存 + Spring 的集成。关于 Redis 服务器的搭建请参考博客《Redhat5.8 环境下编译安装 Redis 并将其注册为系统服务》。

1. 依赖包安装

pom.xml 加入:

[html] view plain copy print?

1
2
3
4
5
6
7
8
9
10
11
12
<!-- redis cache related.....start -->  
<dependency>  
     <groupId>org.springframework.data</groupId>  
     <artifactId>spring-data-redis</artifactId>  
     <version> 1.6 . 0 .RELEASE</version>  
</dependency>  
<dependency>  
     <groupId>redis.clients</groupId>  
     <artifactId>jedis</artifactId>  
     <version> 2.7 . 3 </version>  
</dependency>  
<!-- redis cache related.....end -->

 


2. Spring 项目集成进缓存支持

要启用缓存支持,我们需要创建一个新的 CacheManager bean。CacheManager 接口有很多实现,本文演示的是和 Redis 的集成,自然就是用 RedisCacheManager 了。Redis 不是应用的共享内存,它只是一个内存服务器,就像 MySql 似的,我们需要将应用连接到它并使用某种“语言”进行交互,因此我们还需要一个连接工厂以及一个 Spring 和 Redis 对话要用的 RedisTemplate,这些都是 Redis 缓存所必需的配置,把它们都放在自定义的 CachingConfigurerSupport 中:

[java] view plain copy print?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/** 
  * File Name:RedisCacheConfig.java 
 
  * Copyright Defonds Corporation 2015  
  * All Rights Reserved 
 
  */  
package  com.defonds.bdp.cache.redis;  
   
import  org.springframework.cache.CacheManager;  
import  org.springframework.cache.annotation.CachingConfigurerSupport;  
import  org.springframework.cache.annotation.EnableCaching;  
import  org.springframework.context.annotation.Bean;  
import  org.springframework.context.annotation.Configuration;  
import  org.springframework.data.redis.cache.RedisCacheManager;  
import  org.springframework.data.redis.connection.RedisConnectionFactory;  
import  org.springframework.data.redis.connection.jedis.JedisConnectionFactory;  
import  org.springframework.data.redis.core.RedisTemplate;  
   
/** 
  *  
  * Project Name:bdp  
  * Type Name:RedisCacheConfig  
  * Type Description: 
  *  Author:Defonds 
  * Create Date:2015-09-21 
  *  
  * @version 
  *  
  */  
@Configuration  
@EnableCaching  
public  class  RedisCacheConfig  extends  CachingConfigurerSupport {  
   
     @Bean  
     public  JedisConnectionFactory redisConnectionFactory() {  
         JedisConnectionFactory redisConnectionFactory =  new  JedisConnectionFactory();  
   
         // Defaults  
         redisConnectionFactory.setHostName( "192.168.1.166" );  
         redisConnectionFactory.setPort( 6379 );  
         return  redisConnectionFactory;  
     }  
   
     @Bean  
     public  RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {  
         RedisTemplate<String, String> redisTemplate =  new  RedisTemplate<String, String>();  
         redisTemplate.setConnectionFactory(cf);  
         return  redisTemplate;  
     }  
   
     @Bean  
     public  CacheManager cacheManager(RedisTemplate redisTemplate) {  
         RedisCacheManager cacheManager =  new  RedisCacheManager(redisTemplate);  
   
         // Number of seconds before expiration. Defaults to unlimited (0)  
         cacheManager.setDefaultExpiration( 3000 );  // Sets the default expire time (in seconds)  
         return  cacheManager;  
     }  
       
}




当然也别忘了把这些 bean 注入 Spring,不然配置无效。在 applicationContext.xml 中加入以下:

[html] view plain copy print?

  1. <context:component-scan base-package="com.defonds.bdp.cache.redis" />  


3. 缓存某些方法的执行结果

设置好缓存配置之后我们就可以使用 @Cacheable 注解来缓存方法执行的结果了,比如根据省份名检索城市的 provinceCities 方法和根据 city_code 检索城市的 searchCity 方法:

[java] view plain copy print?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// R  
@Cacheable ( "provinceCities" )  
public  List<City> provinceCities(String province) {  
     logger.debug( "province="  + province);  
     return  this .cityMapper.provinceCities(province);  
}  
   
// R  
@Cacheable ( "searchCity" )  
public  City searchCity(String city_code){  
     logger.debug( "city_code="  + city_code);  
     return  this .cityMapper.searchCity(city_code);     
}  
 
4 . 缓存数据一致性保证
CRUD
  (Create 创建,Retrieve 读取,Update 更新,Delete 删除) 操作中,除了 R 
具备幂等性,其他三个发生的时候都可能会造成缓存结果和数据库不一致。为了保证缓存数据的一致性,在进行 CUD 
操作的时候我们需要对可能影响到的缓存进行更新或者清除。
[java] view plain copy print?
// C  
@CacheEvict (value = {  "provinceCities" }, allEntries =  true )  
public  void  insertCity(String city_code, String city_jb,   
         String province_code, String city_name,  
         String city, String province) {  
     City cityBean =  new  City();  
     cityBean.setCityCode(city_code);  
     cityBean.setCityJb(city_jb);  
     cityBean.setProvinceCode(province_code);  
     cityBean.setCityName(city_name);  
     cityBean.setCity(city);  
     cityBean.setProvince(province);  
     this .cityMapper.insertCity(cityBean);  
}  
// U  
@CacheEvict (value = {  "provinceCities" "searchCity"  }, allEntries =  true )  
public  int  renameCity(String city_code, String city_name) {  
     City city =  new  City();  
     city.setCityCode(city_code);  
     city.setCityName(city_name);  
     this .cityMapper.renameCity(city);  
     return  1 ;  
}  
   
// D  
@CacheEvict (value = {  "provinceCities" "searchCity"  }, allEntries =  true )  
public  int  deleteCity(String city_code) {  
     this .cityMapper.deleteCity(city_code);  
     return  1 ;  
}


业务考虑,本示例用的都是 @CacheEvict 清除缓存。如果你的 CUD 能够返回 City 实例,也可以使用 @CachePut 更新缓存策略。笔者推荐能用 @CachePut 的地方就不要用 @CacheEvict,因为后者将所有相关方法的缓存都清理掉,比如上面三个方法中的任意一个被调用了的话,provinceCities 方法的所有缓存将被清除。

5. 自定义缓存数据 key 生成策略

对于使用 @Cacheable 注解的方法,每个缓存的 key 生成策略默认使用的是参数名+参数值,比如以下方法:

[java] view plain copy print?

  1. @Cacheable("users")  

  2. public User findByUsername(String username)  


这个方法的缓存将保存于 key 为 users~keys 的缓存下,对于 username 取值为 "赵德芳" 的缓存,key 为 "username-赵德芳"。一般情况下没啥问题,二般情况如方法 key 取值相等然后参数名也一样的时候就出问题了,如:

[java] view plain copy print?

  1. @Cacheable("users")  

  2. public Integer getLoginCountByUsername(String username)  


这个方法的缓存也将保存于 key 为 users~keys 的缓存下。对于 username 取值为 "赵德芳" 的缓存,key 也为 "username-赵德芳",将另外一个方法的缓存覆盖掉。
解决办法是使用自定义缓存策略,对于同一业务(同一业务逻辑处理的方法,哪怕是集群/分布式系统),生成的 key 始终一致,对于不同业务则不一致:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Bean  
public  KeyGenerator customKeyGenerator() {  
     return  new  KeyGenerator() {  
         @Override  
         public  Object generate(Object o, Method method, Object... objects) {  
             StringBuilder sb =  new  StringBuilder();  
             sb.append(o.getClass().getName());  
             sb.append(method.getName());  
             for  (Object obj : objects) {  
                 sb.append(obj.toString());  
             }  
             return  sb.toString();  
         }  
     };  
}

于是上述两个方法,对于 username 取值为 "赵德芳" 的缓存,虽然都还是存放在 key 为 users~keys 的缓存下,但由于 key 分别为 "类名-findByUsername-username-赵德芳" 和 "类名-getLoginCountByUsername-username-赵德芳",所以也不会有问题。
这对于集群系统、分布式系统之间共享缓存很重要,真正实现了分布式缓存。
笔者建议:缓存方法的 @Cacheable 最好使用方法名,避免不同的方法的 @Cacheable 值一致,然后再配以以上缓存策略。

6. 缓存的验证

6.1 缓存的验证

为了确定每个缓存方法到底有没有走缓存,我们打开了 MyBatis 的 SQL 日志输出,并且为了演示清楚,我们还清空了测试用 Redis 数据库。
先来验证 provinceCities 方法缓存,Eclipse 启动 tomcat 加载项目完毕,使用 JMeter 调用 /bdp/city/province/cities.json 接口:
使用 JMeter 调用 /bdp/city/province/cities.json 接口.png
Eclipse 控制台输出如下:
Eclipse 控制台输出如下.png
说明这一次请求没有命中缓存,走的是 db 查询。JMeter 再次请求,Eclipse 控制台输出:
Eclipse 控制台输出
标红部分以下是这一次请求的 log,没有访问 db 的 log,缓存命中。查看本次请求的 Redis 存储情况:
查看本次请求的 Redis 存储情况.png
同样可以验证 city_code 为 1492 的 searchCity 方法的缓存是否有效:
同样可以验证 city_code 为 1492 的 searchCity 方法的缓存是否有效.png
图中标红部分是 searchCity 的缓存存储情况。

6.2 缓存一致性的验证

先来验证 insertCity 方法的缓存配置,JMeter 调用 /bdp/city/create.json 接口:
JMeter 调用 /bdp/city/create.json 接口.png
之后看 Redis 存储:
之后看 Redis 存储
可以看出 provinceCities 方法的缓存已被清理掉,insertCity 方法的缓存奏效。
然后验证 renameCity 方法的缓存配置,JMeter 调用 /bdp/city/rename.json 接口:
JMeter 调用 /bdp/city/rename.json 接口.png
之后再看 Redis 存储:
之后再看 Redis 存储.png
searchCity 方法的缓存也已被清理,renameCity 方法的缓存也奏效。

7. 注意事项

  1. 要缓存的 Java 对象必须实现 Serializable 接口,因为 Spring 会将对象先序列化再存入 Redis,比如本文中的 com.defonds.bdp.city.bean.City 类,如果不实现 Serializable 的话将会遇到类似这种错误:nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.defonds.bdp.city.bean.City]]

  2. 缓存的生命周期我们可以配置,然后托管 Spring CacheManager,不要试图通过 redis-cli 命令行去管理缓存。比如 provinceCities 方法的缓存,某个省份的查询结果会被以 key-value 的形式存放在 Redis,key 就是我们刚才自定义生成的 key,value 是序列化后的对象,这个 key 会被放在 key 名为 provinceCities~keys key-value 存储中,参考下图"provinceCities 方法在 Redis 中的缓存情况"。可以通过 redis-cli 使用 del 命令将 provinceCities~keys 删除,但每个省份的缓存却不会被清除。

  3. CacheManager 必须设置缓存过期时间,否则缓存对象将永不过期,这样做的原因如上,避免一些野数据“永久保存”。此外,设置缓存过期时间也有助于资源利用最大化,因为缓存里保留的永远是热点数据。

  4. 缓存适用于读多写少的场合,查询时缓存命中率很低、写操作很频繁等场景不适宜用缓存。

provinceCities方法在Redis中的存储.png

后记

本文完整 Eclipse 下的开发项目示例已上传 CSDN 资源,有兴趣的朋友可以去下载下来参考:http://download.csdn.net/detail/defonds/9137505

参考资料


http://blog.csdn.net/defonds/article/details/48716161















本文转自yunlielai51CTO博客,原文链接:http://blog.51cto.com/4925054/1865971,如需转载请自行联系原作者

相关文章
|
10月前
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
5月前
|
缓存 负载均衡 监控
135_负载均衡:Redis缓存 - 提高缓存命中率的配置与最佳实践
在现代大型语言模型(LLM)部署架构中,缓存系统扮演着至关重要的角色。随着LLM应用规模的不断扩大和用户需求的持续增长,如何构建高效、可靠的缓存架构成为系统性能优化的核心挑战。Redis作为业界领先的内存数据库,因其高性能、丰富的数据结构和灵活的配置选项,已成为LLM部署中首选的缓存解决方案。
|
6月前
|
存储 缓存 NoSQL
Redis专题-实战篇二-商户查询缓存
本文介绍了缓存的基本概念、应用场景及实现方式,涵盖Redis缓存设计、缓存更新策略、缓存穿透问题及其解决方案。重点讲解了缓存空对象与布隆过滤器的使用,并通过代码示例演示了商铺查询的缓存优化实践。
301 1
Redis专题-实战篇二-商户查询缓存
|
5月前
|
缓存 运维 监控
Redis 7.0 高性能缓存架构设计与优化
🌟蒋星熠Jaxonic,技术宇宙中的星际旅人。深耕Redis 7.0高性能缓存架构,探索函数化编程、多层缓存、集群优化与分片消息系统,用代码在二进制星河中谱写极客诗篇。
|
6月前
|
缓存 NoSQL 关系型数据库
Redis缓存和分布式锁
Redis 是一种高性能的键值存储系统,广泛用于缓存、消息队列和内存数据库。其典型应用包括缓解关系型数据库压力,通过缓存热点数据提高查询效率,支持高并发访问。此外,Redis 还可用于实现分布式锁,解决分布式系统中的资源竞争问题。文章还探讨了缓存的更新策略、缓存穿透与雪崩的解决方案,以及 Redlock 算法等关键技术。
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
缓存 Java 数据库
优化您的Spring应用程序:缓存注解的精要指南
优化您的Spring应用程序:缓存注解的精要指南
269 0
|
存储 缓存 Java
Spring缓存注解【@Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig】使用及注意事项
Spring缓存注解【@Cacheable、@CachePut、@CacheEvict、@Caching、@CacheConfig】使用及注意事项
4577 2
|
缓存 NoSQL Java
Spring Cache之本地缓存注解@Cacheable,@CachePut,@CacheEvict使用
SpringCache不支持灵活的缓存时间和集群,适合数据量小的单机服务或对一致性要求不高的场景。`@EnableCaching`启用缓存。`@Cacheable`用于缓存方法返回值,`value`指定缓存名称,`key`定义缓存键,可按SpEL编写,`unless`决定是否不缓存空值。当在类上使用时,类内所有方法都支持缓存。`@CachePut`每次执行方法后都会更新缓存,而`@CacheEvict`用于清除缓存,支持按键清除或全部清除。Spring Cache结合Redis可支持集群环境。
1791 6
|
缓存 NoSQL Java
Spring Cache-缓存注解(二)
Spring Cache-缓存注解(二)
349 0