`
dwj147258
  • 浏览: 191950 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

spring集成redis

阅读更多

1. 依赖包安装

pom.xml 加入:

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


当然也别忘了把这些 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. // R  
  2. @Cacheable("provinceCities")  
  3. public List<City> provinceCities(String province) {  
  4.     logger.debug("province=" + province);  
  5.     return this.cityMapper.provinceCities(province);  
  6. }  
  7.   
  8. // R  
  9. @Cacheable("searchCity")  
  10. public City searchCity(String city_code){  
  11.     logger.debug("city_code=" + city_code);  
  12.     return this.cityMapper.searchCity(city_code);     
  13. }  

 

4. 缓存数据一致性保证

CRUD (Create 创建,Retrieve 读取,Update 更新,Delete 删除) 操作中,除了 R 具备幂等性,其他三个发生的时候都可能会造成缓存结果和数据库不一致。为了保证缓存数据的一致性,在进行 CUD 操作的时候我们需要对可能影响到的缓存进行更新或者清除。

[java] view plain copy
 
 print?
  1. // C  
  2. @CacheEvict(value = { "provinceCities"}, allEntries = true)  
  3. public void insertCity(String city_code, String city_jb,   
  4.         String province_code, String city_name,  
  5.         String city, String province) {  
  6.     City cityBean = new City();  
  7.     cityBean.setCityCode(city_code);  
  8.     cityBean.setCityJb(city_jb);  
  9.     cityBean.setProvinceCode(province_code);  
  10.     cityBean.setCityName(city_name);  
  11.     cityBean.setCity(city);  
  12.     cityBean.setProvince(province);  
  13.     this.cityMapper.insertCity(cityBean);  
  14. }  
  15. // U  
  16. @CacheEvict(value = { "provinceCities""searchCity" }, allEntries = true)  
  17. public int renameCity(String city_code, String city_name) {  
  18.     City city = new City();  
  19.     city.setCityCode(city_code);  
  20.     city.setCityName(city_name);  
  21.     this.cityMapper.renameCity(city);  
  22.     return 1;  
  23. }  
  24.   
  25. // D  
  26. @CacheEvict(value = { "provinceCities""searchCity" }, allEntries = true)  
  27. public int deleteCity(String city_code) {  
  28.     this.cityMapper.deleteCity(city_code);  
  29.     return 1;  
  30. }  


业务考虑,本示例用的都是 @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 始终一致,对于不同业务则不一致:

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


于是上述两个方法,对于 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

分享到:
评论

相关推荐

    Spring集成redis集群

    **Spring集成Redis集群详解** 在现代的Web应用程序开发中,数据缓存扮演着至关重要的角色,而Redis作为一款高性能的键值数据存储系统,被广泛应用于缓存、消息队列等多个场景。当业务规模扩大,单机Redis可能无法...

    spring 集成redis

    以上就是Spring集成Redis的基本流程。通过这个集成,你可以充分利用Redis的高性能特性,提高应用程序的响应速度和处理能力。同时,Spring Data Redis提供的高级功能,如事务支持、Key的过期策略、lua脚本执行等,都...

    spring集成redis单节点、集群、哨兵配置

    本文将深入探讨如何在Spring项目中集成Redis的单节点、集群和哨兵模式。 首先,让我们来看**单节点配置**。在Spring中集成Redis单节点,我们需要在Spring的配置文件中定义RedisConnectionFactory。这通常通过...

    spring集成redis源码

    spring和redis集成有很多方式,看到网上很多都是使用redistemplate自己去做redis 的一些操作,但是对于我们开发来说,肯定是使用越方便越好,于是乎就有了spring的对redis或者memcahe这些换成框架的封装,只需要引入...

    spring集成redis,集成redis集群

    当我们谈论“Spring集成Redis集群”时,这意味着我们要在Spring应用中配置和使用多个Redis实例,形成一个高可用、高并发的数据库解决方案。 首先,让我们深入理解Spring对Redis支持的基本概念。Spring Data Redis...

    spring集成redis源代码

    让我们深入探讨Spring集成Redis的相关知识点。 1. **Spring Data Redis简介** Spring Data Redis项目是为了简化Redis在Java应用中的使用而设计的。它提供了高度抽象的API,可以方便地操作Redis数据结构,如字符串...

    spring集成redis需要的jar包.rar

    "spring集成redis需要的jar包.rar"这个压缩包包含的两个关键文件,`jedis-3.1.0.jar`和`spring-data-redis-2.1.9.RELEASE.jar`,就是这样的关键库。 首先,`jedis-3.1.0.jar`是Jedis客户端,它是Java语言连接Redis...

    java spring集成redis所需库包

    总之,Java Spring集成Redis涉及的库包主要包括Spring Data Redis、Jedis或Lettuce客户端,以及相应的配置和操作API。在集成过程中,要注意依赖管理,确保所有库包版本兼容,以避免出现不兼容问题。通过正确配置和...

    spring集成redis所需jar包

    包括: commons-pool-1.6,spring-data-redis-1.0.1.RELEASE,spring-data-redis-1.0.1.RELEASE-javadoc,spring-data-redis-1.0.1.RELEASE-sources,jedis-2.1.0

    demo:redis作为mybatis的第三方缓存以及spring集成redis的直接操作数据库

    spring集成redis的demo项目。其中包括redis作为mybatis的第三方缓存配置和redis直接操作缓存数据库的集成。说明:将application.properties中数据源的修改成你的配置。若你只想看spring集成redis的操作,则可以将...

    spring集成redis集群需要的jar.zip

    Spring + redis集群的集成 spring-data-redis-1.8.1.RELEASE.jar jedis-2.9.0.jar spring-data-commons-1.8.1.RELEASE.jar commons-pool2-2.4.2.jar

    spring 集成 redis 使用例子

    首先,让我们理解Spring集成Redis的基础。Redis是一个高性能的键值对数据存储系统,常用于缓存和消息队列等场景。Spring提供了`spring-data-redis`模块,使得与Redis的交互变得简单。通过使用Spring Data Redis,...

    spring集成redis实现聊天室功能

    首先,我们需要理解Spring集成Redis的基础配置。在Spring项目中,我们通常通过Spring Data Redis模块来与Redis进行交互。这涉及到以下步骤: 1. 添加依赖:在项目的`pom.xml`或`build.gradle`文件中,引入Spring ...

    Spring集成Redis集群的配置文件

    Spring集成Redis集群的配置文件

    Spring集成Redis进行数据缓存

    在SpringMVC中集成Redis,可以显著减少对数据库的访问,提高应用性能。 **Spring与Redis的集成** 1. **配置Redis连接**: 在Spring的配置文件中,我们需要定义一个`JedisConnectionFactory`来建立与Redis服务器的...

    spring集成redis的使用demo

    本教程将探讨如何在Spring MVC项目中集成Redis,实现数据的存储和删除操作。 首先,我们要在项目中添加Redis的相关依赖。在`pom.xml`文件中,我们需要引入Spring Data Redis和Jedis库,如下所示: ```xml ...

    Spring集成Redis

    **Spring集成Redis** 在现代Web应用开发中,Redis作为一个高性能的键值对数据存储系统,常被用作缓存和消息中间件。Spring框架提供了强大的支持来帮助开发者轻松地将Redis集成到Java应用中。本篇文章将深入探讨如何...

Global site tag (gtag.js) - Google Analytics