服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解Redis 缓存 + Spring 的集成示例

详解Redis 缓存 + Spring 的集成示例

2020-09-06 15:44Defonds Java教程

本篇文章主要介绍了Redis 缓存 + Spring 的集成示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

《整合 spring 4(包括mvc、context、orm) + mybatis 3 示例》一文简要介绍了最新版本的 spring mvc、ioc、mybatis orm 三者的整合以及声明式事务处理。现在我们需要把缓存也整合进来,缓存我们选用的是 redis,本文将在该文示例基础上介绍 redis 缓存 + spring 的集成。

1. 依赖包安装

pom.xml 加入:

?
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 中:

?
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 中加入以下:

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
// 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 操作的时候我们需要对可能影响到的缓存进行更新或者清除。

?
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
// 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 生成策略默认使用的是参数名+参数值,比如以下方法:

?
1
2
@cacheable("users")
public user findbyusername(string username)

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

?
1
2
@cacheable("users")
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 接口:

详解Redis 缓存 + Spring 的集成示例

eclipse 控制台输出如下:

详解Redis 缓存 + Spring 的集成示例

说明这一次请求没有命中缓存,走的是 db 查询。jmeter 再次请求,eclipse 控制台输出:

输出:
详解Redis 缓存 + Spring 的集成示例

标红部分以下是这一次请求的 log,没有访问 db 的 log,缓存命中。查看本次请求的 redis 存储情况:

详解Redis 缓存 + Spring 的集成示例

同样可以验证 city_code 为 1492 的 searchcity 方法的缓存是否有效:

详解Redis 缓存 + Spring 的集成示例

图中标红部分是 searchcity 的缓存存储情况。

6.2 缓存一致性的验证

先来验证 insertcity 方法的缓存配置,jmeter 调用 /bdp/city/create.json 接口:

详解Redis 缓存 + Spring 的集成示例

之后看 redis 存储:

详解Redis 缓存 + Spring 的集成示例

可以看出 provincecities 方法的缓存已被清理掉,insertcity 方法的缓存奏效。

然后验证 renamecity 方法的缓存配置,jmeter 调用 /bdp/city/rename.json 接口:

详解Redis 缓存 + Spring 的集成示例

之后再看 redis 存储:

详解Redis 缓存 + Spring 的集成示例

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. 缓存适用于读多写少的场合,查询时缓存命中率很低、写操作很频繁等场景不适宜用缓存。

详解Redis 缓存 + Spring 的集成示例

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://blog.csdn.net/defonds/article/details/48716161

延伸 · 阅读

精彩推荐