Springboot 2.X中Spring-cache与redis整合

一、本次案例

Springboot中Spring-cache与redis整合。这也是一个不错的框架,与spring的事务使用类似,只要添加一些注解方法,就可以动态的去操作缓存了,减少代码的操作。如果这些注解不满足项目的需求,我们也可以参考spring-cache的实现思想,使用AOP代理+缓存操作来管理缓存的使用。

在这个例子中我使用的是redis,当然,因为spring-cache的存在,我们可以整合多样的缓存技术,例如Ecache、Mamercache等。

二、创建springBoot 项目  king-cache

图片[1]-Springboot 2.X中Spring-cache与redis整合-第五维

  1. 在pom.xml中添加以下依赖
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-cache</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-data-redis</artifactId>
  8. </dependency>

 

三、redis客户端配置

无论使用spring-boot的哪个版本,我们都需要先配置redis连接,两个版本的redis客户端连接池使用有所不同。

spring-boot版本 默认客户端类型
1.5.x jedis
2.x lettuce

在1.5.x中,我们配置jedis连接池只需要配置 spring.redis.pool.* 开始的配置即可,如下配置

  1. spring.redis.pool.max-active=8
  2. spring.redis.pool.max-wait=-1
  3. spring.redis.pool.min-idle=0
  4. spring.redis.pool.max-idle=8

但在2.x版本中由于引入了不同的客户端,需要指定配置哪种连接池,如下配置

在application.properties中添加如下代码:

  1. #jedis客户端
  2. server.port=8080
  3. spring.cache.type=redis
  4. spring.redis.host=192.168.140.130 # server host
  5. spring.redis.password= 123456
  6. spring.redis.port= 6379
  7. spring.redis.jedis.pool.max-active=8
  8. spring.redis.jedis.pool.max-wait=-1ms
  9. spring.redis.jedis.pool.min-idle=0
  10. spring.redis.jedis.pool.max-idle=8
  11. #lettuce客户端
  12. spring.redis.lettuce.pool.min-idle=0
  13. spring.redis.lettuce.pool.max-idle=8
  14. spring.redis.lettuce.pool.max-wait=-1ms
  15. spring.redis.lettuce.pool.max-active=8
  16. spring.redis.lettuce.shutdown-timeout=100ms

除此之外还可以看到时间配置上还需要带上对应的单位。

四、JavaConfig方式配置

通用配置方式只能满足整个程序所有缓存都采用相同公共配置的方式,如果需要特殊处理,如我们的案列,则需要自己采用代码的方式来配置。
采用代码的方式,只要需要配置的是CacheMananger,采用Redis时具体实现我们需要使用其子类RedisCacheMananger来做配置

  1. 创建redis的配置类RedisConfig.java
  2. 注意一定要在类上加上以下两个注解:
  3.     @Configuration  可理解为用spring的时候xml里面的<beans>标签
  4.     @EnableCaching 注解是spring framework中的注解驱动的缓存管理功能。
  1. package com.answer.config;
  2. import java.lang.reflect.Method;
  3. import java.time.Duration;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import org.springframework.cache.CacheManager;
  7. import org.springframework.cache.annotation.CachingConfigurerSupport;
  8. import org.springframework.cache.annotation.EnableCaching;
  9. import org.springframework.cache.interceptor.KeyGenerator;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  13. import org.springframework.data.redis.cache.RedisCacheManager;
  14. import org.springframework.data.redis.cache.RedisCacheWriter;
  15. import org.springframework.data.redis.connection.RedisConnectionFactory;
  16. import org.springframework.data.redis.core.RedisTemplate;
  17. import org.springframework.data.redis.core.StringRedisTemplate;
  18. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  19. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  20. import com.fasterxml.jackson.annotation.PropertyAccessor;
  21. import com.fasterxml.jackson.databind.ObjectMapper;
  22. /**
  23. * <p>redis缓存配置</p>
  24. * Created by zhezhiyong@163.com on 2017/9/21.
  25. */
  26. @Configuration
  27. @EnableCaching
  28. public class RedisConfig extends CachingConfigurerSupport {
  29. @Bean
  30. public KeyGenerator KeyGenerator() {
  31. return new KeyGenerator() {
  32. @Override
  33. public Object generate(Object target, Method method, Object… params) {
  34. StringBuilder sb = new StringBuilder();
  35. sb.append(target.getClass().getName());
  36. sb.append(method.getName());
  37. for (Object obj : params) {
  38. sb.append(obj.toString());
  39. }
  40. return sb.toString();
  41. }
  42. };
  43. }
  44. /* @Bean
  45. public CacheManager cacheManager(RedisTemplate redisTemplate) {
  46. RedisCacheManager manager = new RedisCacheManager(redisTemplate);
  47. manager.setUsePrefix(true);
  48. RedisCachePrefix cachePrefix = new RedisPrefix(“prefix”);
  49. manager.setCachePrefix(cachePrefix);
  50. // 整体缓存过期时间
  51. manager.setDefaultExpiration(3600L);
  52. // 设置缓存过期时间。key和缓存过期时间,单位秒
  53. Map<String, Long> expiresMap = new HashMap<>();
  54. expiresMap.put(“user”, 1000L);
  55. manager.setExpires(expiresMap);
  56. return manager;
  57. }*/
  58. @Bean
  59. CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
  60. //初始化一个RedisCacheWriter
  61. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
  62. //设置CacheManager的值序列化方式为JdkSerializationRedisSerializer,但其实RedisCacheConfiguration默认就是使用StringRedisSerializer序列化key,JdkSerializationRedisSerializer序列化value,所以以下注释代码为默认实现
  63. //ClassLoader loader = this.getClass().getClassLoader();
  64. //JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
  65. //RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair.fromSerializer(jdkSerializer);
  66. //RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair);
  67. RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
  68. //设置默认超过期时间是30秒
  69. defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
  70. //初始化RedisCacheManager
  71. RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
  72. return cacheManager;
  73. }
  74. @Bean
  75. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  76. StringRedisTemplate template = new StringRedisTemplate(factory);
  77. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  78. ObjectMapper om = new ObjectMapper();
  79. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  80. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  81. jackson2JsonRedisSerializer.setObjectMapper(om);
  82. template.setValueSerializer(jackson2JsonRedisSerializer);
  83. template.afterPropertiesSet();
  84. return template;
  85. }
  86. }

以上代码中RedisCacheConfiguration类为2.x新增的配置类,增加了几个配置项。这里比较奇怪的是调用它的配置方法每一次都会重新生成一个配置对象,而不是在原对象上直接修改参数值,这一点本人没搞懂作者为何要选择这种方式。

到这里基本的配置就已经完成了

五、具体使用

如果我们想在其他项目中添加该微服务想进行缓存的操作,需依赖king-cache模块:

  1. <!– redis-cache 工具类 –>
  2. <dependency>
  3. <groupId>com.answer</groupId>
  4. <artifactId>king-cache</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. </dependency>

六、测试Demo——新建项目:king-cache-1

图片[2]-Springboot 2.X中Spring-cache与redis整合-第五维

添加以下依赖:

  1. <!– redis-cache 工具类 –>
  2. <dependency>
  3. <groupId>com.answer</groupId>
  4. <artifactId>king-cache</artifactId>
  5. <version>0.0.1-SNAPSHOT</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.google.guava</groupId>
  9. <artifactId>guava</artifactId>
  10. <version>19.0</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.projectlombok</groupId>
  14. <artifactId>lombok</artifactId>
  15. <scope>compile</scope>
  16. </dependency>

依上图所示分别创建以下实例:

Info.java

  1. package com.answer.entity;
  2. import java.io.Serializable;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. /**
  6. * <p></p>
  7. * Created by zhezhiyong@163.com on 2017/9/22.
  8. */
  9. @Data
  10. @AllArgsConstructor
  11. public class Info implements Serializable{
  12. /**
  13. * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
  14. */
  15. private static final long serialVersionUID = 5457507957150215600L;
  16. public Info(String string, String string2) {
  17. // TODO Auto-generated constructor stub
  18. }
  19. public String getPhone() {
  20. return phone;
  21. }
  22. public void setPhone(String phone) {
  23. this.phone = phone;
  24. }
  25. public String getAddress() {
  26. return address;
  27. }
  28. public void setAddress(String address) {
  29. this.address = address;
  30. }
  31. private String phone;
  32. private String address;
  33. }

User.java

  1. package com.answer.entity;
  2. import java.io.Serializable;
  3. import lombok.AllArgsConstructor;
  4. import lombok.Data;
  5. import lombok.NoArgsConstructor;
  6. /**
  7. * <p></p>
  8. * Created by zhezhiyong@163.com on 2017/9/21.
  9. */
  10. @Data
  11. @AllArgsConstructor
  12. @NoArgsConstructor
  13. public class User implements Serializable{
  14. /**
  15. * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
  16. */
  17. private static final long serialVersionUID = 1L;
  18. public Long getId() {
  19. return id;
  20. }
  21. public void setId(Long id) {
  22. this.id = id;
  23. }
  24. public String getName() {
  25. return name;
  26. }
  27. public void setName(String name) {
  28. this.name = name;
  29. }
  30. public String getPassword() {
  31. return password;
  32. }
  33. public void setPassword(String password) {
  34. this.password = password;
  35. }
  36. private Long id;
  37. private String name;
  38. private String password;
  39. }

IndexController.java

  1. package com.answer.web;
  2. import java.util.List;
  3. import java.util.Map;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import com.answer.entity.User;
  10. import com.answer.service.UserService;
  11. import com.google.common.collect.ImmutableMap;
  12. /**
  13. * <p></p>
  14. * Created by zhezhiyong@163.com on 2017/9/21.
  15. */
  16. @RestController
  17. public class IndexController {
  18. @Autowired
  19. private UserService userService;
  20. @GetMapping(“/users”)
  21. @ResponseBody
  22. public List<User> users() {
  23. return userService.list();
  24. }
  25. @GetMapping(“/user/{id}”)
  26. @ResponseBody
  27. public User findUserById(@PathVariable(“id”) Long id) {
  28. return userService.findUserById(id);
  29. }
  30. @GetMapping(“/upuser/{id}”)
  31. @ResponseBody
  32. public User upuser(@PathVariable(“id”) Long id) {
  33. return userService.upuser(id);
  34. }
  35. @GetMapping(“/info/{id}”)
  36. @ResponseBody
  37. public User findInfoById(@PathVariable(“id”) Long id) {
  38. return userService.findInfoById(id);
  39. }
  40. @GetMapping(“/user/{id}/{name}”)
  41. @ResponseBody
  42. public Map update(@PathVariable(“id”) Long id, @PathVariable(“name”) String name) {
  43. User user = userService.findUserById(id);
  44. user.setName(name);
  45. userService.update(user);
  46. return ImmutableMap.of(“ret”, 0, “msg”, “ok”);
  47. }
  48. }

UserService.java

  1. package com.answer.service;
  2. import java.util.List;
  3. import com.answer.entity.User;
  4. /**
  5. * <p></p>
  6. * Created by zhezhiyong@163.com on 2017/9/21.
  7. */
  8. public interface UserService {
  9. List<User> list();
  10. User findUserById(Long id);
  11. User findInfoById(Long id);
  12. void update(User user);
  13. void remove(Long id);
  14. User upuser(Long id);
  15. }

UserServiceImpl.java

  1. package com.answer.service.impl;
  2. import java.util.Arrays;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6. import org.springframework.cache.annotation.CacheEvict;
  7. import org.springframework.cache.annotation.CachePut;
  8. import org.springframework.cache.annotation.Cacheable;
  9. import org.springframework.stereotype.Service;
  10. import com.answer.entity.Info;
  11. import com.answer.entity.User;
  12. import com.answer.service.UserService;
  13. import lombok.extern.slf4j.Slf4j;
  14. /**
  15. * <p></p>
  16. * Created by zhezhiyong@163.com on 2017/9/21.
  17. */
  18. @Service
  19. @Slf4j
  20. public class UserServiceImpl implements UserService {
  21. private Map<Long, User> userMap = new HashMap<>();
  22. private Map<Long, Info> infoMap = new HashMap<>();
  23. public UserServiceImpl() {
  24. User u1=new User();
  25. u1.setId(1L);
  26. u1.setName(“1111”);
  27. u1.setPassword(“11223434”);
  28. User u2=new User();
  29. u2.setId(1L);
  30. u2.setName(“1111”);
  31. u2.setPassword(“11223434”);
  32. User u3=new User();
  33. u3.setId(1L);
  34. u3.setName(“1111”);
  35. u3.setPassword(“11223434”);
  36. userMap.put(1L,u1);
  37. userMap.put(2L,u2);
  38. userMap.put(3L,u3);
  39. infoMap.put(1L, new Info(“18559198715”, “福州市”));
  40. }
  41. @Override
  42. public List list() {
  43. return Arrays.asList(userMap.values().toArray());
  44. }
  45. @Override
  46. @Cacheable(value = “user”, key = “‘user’.concat(#id.toString())”)
  47. public User findUserById(Long id) {
  48. //log.info(“findUserById query from db, id: {}”, id);
  49. System.out.println(“findUserById query from db, id: {}======”+id);
  50. return userMap.get(id);
  51. }
  52. @Override
  53. @Cacheable(value = “info”, key = “‘info’.concat(#id.toString())”)
  54. public User findInfoById(Long id) {
  55. // log.info(“findInfoById query from db, id: {}”, id);
  56. System.out.println(“findUserById query from db, id: {}======”+id);
  57. return userMap.get(id);
  58. }
  59. @Override
  60. @CachePut(value = “user”, key = “‘user’.concat(#user.id.toString())”)
  61. public void update(User user) {
  62. //log.info(“update db, user: {}”, user.toString());
  63. System.out.println(“findUserById query from db, id: {}======”);
  64. userMap.put(user.getId(), user);
  65. }
  66. @Override
  67. @CacheEvict(value = “user”, key = “‘user’.concat(#id.toString())”)
  68. public void remove(Long id) {
  69. //log.info(“remove from db, id: {}”, id);
  70. System.out.println(“findUserById query from db, id: {}======”);
  71. userMap.remove(id);
  72. }
  73. @Override
  74. @CacheEvict(value = “user”, key = “‘user’.concat(#id.toString())”)
  75. public User upuser(Long id) {
  76. User d= userMap.get(id);
  77. d.setName(“000000000000000000000000000000000000000000000000”);
  78. return d;
  79. }
  80. }

注意:启动项目前一定要对king-cache进行打包(右键项目:Run As —Maven Install)

然后:king-cache-1 右键 maven —Update Project

最后:以Debug 模式启动 项目:king-cache-1

在以下方法出添加断点:

然后多次访问:http://localhost:8080/user/3

你会发现第一次进入断点,后面几次不再进入断点.

一定要添加上这个注解:@Cacheable

 

图片[3]-Springboot 2.X中Spring-cache与redis整合-第五维

项目源码下载地址: https://download.csdn.net/download/guokezhongdeyuzhou/10322780

注意以下注解的作用:

缓存的注解介绍

@Cacheable 触发缓存入口

@CacheEvict 触发移除缓存

@CacahePut 更新缓存

@Caching 将多种缓存操作分组

@CacheConfig 类级别的缓存注解,允许共享缓存名称

@CacheConfig

该注解是可以将缓存分类,它是类级别的注解方式。我们可以这么使用它。
这样的话,UseCacheRedisService的所有缓存注解例如@Cacheable的value值就都为user。

  1. @CacheConfig(cacheNames = “user”)
  2. @Service
  3. public class UseCacheRedisService {}

在redis的缓存中显示如下

  1. 127.0.0.1:6379> keys *
  2. 1) user~keys
  3. 2) user_1
  4. 127.0.0.1:6379> get user~keys
  5. (error) WRONGTYPE Operation against a key holding the wrong kind of value
  6. 127.0.0.1:6379> type user~keys
  7. zset
  8. 127.0.0.1:6379> zrange user~keys 0 10
  9. 1) user_1

我们注意到,生成的user~keys,它是一个zset类型的key,如果使用get会报WRONGTYPE Operation against a key holding the wrong kind of value。这个问题坑了我很久

@Cacheable

一般用于查询操作,根据key查询缓存.

  1. 如果key不存在,查询db,并将结果更新到缓存中。
  2. 如果key存在,直接查询缓存中的数据。

查询的例子,当第一查询的时候,redis中不存在key,会从db中查询数据,并将返回的结果插入到redis中。

  1. @Cacheable
  2. public List<User> selectAllUser(){
  3. return userMapper.selectAll();
  4. }

调用方式。

  1. @Test
  2. public void selectTest(){
  3. System.out.println(“===========第一次调用=======”);
  4. List<User> list = useCacheRedisService.selectAllUser();
  5. System.out.println(“===========第二次调用=======”);
  6. List<User> list2 = useCacheRedisService.selectAllUser();
  7. for (User u : list2){
  8. System.out.println(“u = “ + u);
  9. }
  10. }

打印结果,大家也可以试一试
只输出一次sql查询的语句,说明第二次查询是从redis中查到的。

  1. ===========第一次调用=======
  2. keyGenerator=com.lzl.redisService.UseCacheRedisService.selectAllUser.
  3. keyGenerator=com.lzl.redisService.UseCacheRedisService.selectAllUser.
  4. DEBUG [main] ==> Preparing: SELECT id,name,sex,age,password,account FROM user
  5. DEBUG [main] – ==> Parameters:
  6. DEBUG [main] – <== Total: 1
  7. ===========第二次调用=======
  8. keyGenerator=com.lzl.redisService.UseCacheRedisService.selectAllUser.
  9. u = User{id=1, name=‘fsdfds’, sex=‘fdsfg’, age=24, password=‘gfdsg’, account=‘gfds’}

redis中的结果
我们可以看到redis中已经存在
com.lzl.redisService.UseCacheRedisService.selectAllUser.记录了。
这么长的一串字符key是根据自定义key值生成的。

  1. 127.0.0.1:6379> keys *
  2. 1) “user~keys
  3. 2) “com.lzl.redisService.UseCacheRedisService.selectAllUser.”
  4. 3) “user_1
  5. 127.0.0.1:6379> get com.lzl.redisService.UseCacheRedisService.selectAllUser.
  6. [\”java.util.ArrayList\”,[[\”com.lzl.bean.User\”,{\”id\”:1,\”name\”:\”fsdfds\”,\”sex\”:\”fdsfg\”,\”age\”:24,\”password\”:\”gfdsg\”,\”account\”:\”gfds\”}]]]

@CachePut

一般用于更新和插入操作,每次都会请求db
通过key去redis中进行操作。
1. 如果key存在,更新内容
2. 如果key不存在,插入内容。

  1. /**
  2. * 单个user对象的插入操作,使用user+id
  3. * @param user
  4. * @return
  5. */
  6. @CachePut(key = “\”user_\” + #user.id”)
  7. public User saveUser(User user){
  8. userMapper.insert(user);
  9. return user;
  10. }

redis中的结果
多了一条记录user_2

  1. 127.0.0.1:6379> keys *
  2. 1) “user~keys”
  3. 2) “user_2”
  4. 3) “com.lzl.redisService.UseCacheRedisService.selectAllUser.”
  5. 4) “user_1”
  6. 127.0.0.1:6379> get user_2
  7. [\”com.lzl.bean.User\,{\”id\:2,\”name\:\”fsdfds\,\”sex\:\”fdsfg\,\”age\:24,\”password\:\”gfdsg\,\”account\:\”gfds\}]

@CacheEvict

根据key删除缓存中的数据。allEntries=true表示删除缓存中的所有数据。

  1. @CacheEvict(key = “\”user_\” + #id”)
  2. public void deleteById(Integer id){
  3. userMapper.deleteByPrimaryKey(id);
  4. }

测试方法

  1. @Test
  2. public void deleteTest(){
  3. useCacheRedisService.deleteById(1);
  4. }

redis中的结果
user_1已经移除掉。

  1. 127.0.0.1:6379> keys *
  2. 1) user~keys
  3. 2) user_2
  4. 3) com.lzl.redisService.UseCacheRedisService.selectAllUser.”

测试allEntries=true时的情形。

  1. @Test
  2. public void deleteAllTest(){
  3. useCacheRedisService.deleteAll();
  4. }
  5. @CacheEvict(allEntries = true)
  6. public void deleteAll(){
  7. userMapper.deleteAll();
  8. }

redis中的结果
redis中的数据已经全部清空

  1. 127.0.0.1:6379> keys *
  2. (empty list or set)

@Caching

通过注解的属性值可以看出来,这个注解将其他注解方式融合在一起了,我们可以根据需求来自定义注解,并将前面三个注解应用在一起

  1. public @interface Caching {
  2. Cacheable[] cacheable() default {};
  3. CachePut[] put() default {};
  4. CacheEvict[] evict() default {};
  5. }

使用例子如下

  1. @Caching(
  2. put = {
  3. @CachePut(value = “user”, key = “\”user_\” + #user.id”),
  4. @CachePut(value = “user”, key = “#user.name”),
  5. @CachePut(value = “user”, key = “#user.account”)
  6. }
  7. )
  8. public User saveUserByCaching(User user){
  9. userMapper.insert(user);
  10. return user;
  11. }
  1. @Test
  2. public void saveUserByCachingTest(){
  3. User user = new User();
  4. user.setName(“dkjd”);
  5. user.setAccount(“dsjkf”);
  6. useCacheRedisService.saveUserByCaching(user);
  7. }

redis中的执行结果
一次添加三个key

  1. 127.0.0.1:6379> keys *
  2. 1) “user~keys”
  3. 2) “dsjkf”
  4. 3) “dkjd”
  5. 4) “user_3”
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享