免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2812 | 回复: 0

SpringBoot集成Redis来实现缓存技术方案 [复制链接]

论坛徽章:
1
15-16赛季CBA联赛之同曦
日期:2017-01-17 18:19:30
发表于 2017-07-28 15:14 |显示全部楼层
概述
在我们的日常项目开发过程中缓存是无处不在的,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用现在非常流行的NoSQL数据库(Redis)来实现我们的缓存需求。

Redis简介
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用作数据库、缓存和消息中间件,Redis 的优势包括它的速度、支持丰富的数据类型、操作原子性,以及它的通用性。

案例整合
本案例是在之前一篇SpringBoot + Mybatis + RESTful的基础上来集成Redis的,所以大家如有什么不明白的地方可以前往https://my.oschina.net/feinik/blog/879266,由于篇幅原因这里不一一贴出所有的代码,具体完整案例代码可以看这里:https://github.com/AIFEINIK/SpringBoot-Learn/tree/master/spring-boot-redis2,关于Redis如何安装可自行google。

1、在Maven pom.xml文件中加入Redis包
  1. <!--redis-->
  2. <dependency>
  3.     <groupId>org.springframework.boot</groupId>
  4.     <artifactId>spring-boot-starter-redis</artifactId>
  5.     <version>${boot.version}</version>
  6. </dependency>
复制代码
2、SpringBoot配置文件中配置Redis连接(YAML方式配置)
  1. spring:
  2.     application:
  3.         name: spring-boot-redis
  4.     redis:
  5.         host: 192.168.145.132
  6.         port: 6379
  7.         timeout: 20000
  8.         cluster:
  9.             nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002
  10.             maxRedirects: 6
  11.         pool:
  12.             max-active: 8
  13.             min-idle: 0
  14.             max-idle: 8
  15.             max-wait: -1
复制代码
解释:本配置采用Redis一主三从的的配置方式来提高缓存的吞吐量

3、Redis配置类
  1. @Configuration
  2. public class RedisConfig {

  3.    @Bean
  4.    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
  5.       RedisTemplate<Object, Object> template = new RedisTemplate<>();
  6.       template.setConnectionFactory(connectionFactory);

  7.       //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
  8.       Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

  9.       ObjectMapper mapper = new ObjectMapper();
  10.       mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  11.       mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  12.       serializer.setObjectMapper(mapper);

  13.       template.setValueSerializer(serializer);
  14.       //使用StringRedisSerializer来序列化和反序列化redis的key值
  15.       template.setKeySerializer(new StringRedisSerializer());
  16.       template.afterPropertiesSet();
  17.       return template;
  18.    }
  19. }
复制代码
解释:SpringBoot提供了对Redis的自动配置功能,在RedisAutoConfiguration中默认为我们配置了JedisConnectionFactory(客户端连接)、RedisTemplate以及StringRedisTemplate(数据操作模板),其中StringRedisTemplate模板只针对键值对都是字符型的数据进行操作,本示例采用RedisTemplate作为数据操作模板,该模板默认采用JdkSerializationRedisSerializer的二进制数据序列化方式,为了方便演示本示例采用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值,使用StringRedisSerializer来序列化和反序列化redis的key值。

4、Service层应用缓存(注解方式)
  1. @Service
  2. public class PersonService {

  3.     @Autowired
  4.     private PersonRepo personRepo;

  5.    /**
  6.      * @Cacheable 应用到读取数据的方法上,先从缓存中读取,如果没有再从DB获取数据,然后把数据添加到缓存中
  7.     * unless 表示条件表达式成立的话不放入缓存
  8.      * @param username
  9.      * @return
  10.      */
  11.     @Cacheable(value = "user", key = "#root.targetClass + #username", unless = "#result eq null")
  12.     public Person getPersonByName(String username) {
  13.         Person person = personRepo.getPersonByName(username);
  14.         return person;
  15.     }

  16.    /**
  17.     * @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存
  18.      * @param person
  19.      * @return
  20.      */
  21.     @CachePut(value = "user", key = "#root.targetClass + #result.username", unless = "#person eq null")
  22.     public Person savePerson(Person person) {
  23.         return personRepo.savePerson(person);
  24.     }

  25.    /**
  26.     * @CacheEvict 应用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据
  27.      * @param username
  28.      * @return
  29.      */
  30.     @CacheEvict(value = "user", key = "#root.targetClass + #username", condition = "#result eq true")
  31.     public boolean removePersonByName(String username) {
  32.         return personRepo.removePersonByName(username) > 0;
  33.     }

  34.     public boolean isExistPersonName(Person person) {
  35.         return personRepo.existPersonName(person) > 0;
  36.     }
  37. }
复制代码
解释:

1、这里的缓存key为简单的字符串组合,也可根据具体需要实现自定义的Key生成器,然后在注解中使用keyGenerator来引用。

2、Spring Cache提供了一些供我们使用的SpEL上下文数据,通过#来引用,具体可查看Spring官网:http://docs.spring.io/spring/doc ... #cache-spel-context

5、数据访问资源类
  1. @Component
  2. @Path("personMgr")
  3. public class PersonMgrResource {

  4.     @Autowired
  5.     private PersonService personService;

  6.     @GET
  7.     @Path("getPersonByName")
  8.     @Produces(MediaType.APPLICATION_JSON)
  9.     public JsonResp getPersonByName(@QueryParam("username") String username) {
  10.         Person person = personService.getPersonByName(username);
  11.         return JsonResp.success(person);
  12.     }

  13.     @POST
  14.     @Path("removePersonByName")
  15.     @Produces(MediaType.APPLICATION_JSON)
  16.     public JsonResp removePersonByName(@QueryParam("username") String username) {
  17.         if (personService.removePersonByName(username)) {
  18.             return JsonResp.success();
  19.         }
  20.         return JsonResp.fail("系统错误!");
  21.     }

  22.     @POST
  23.     @Path("savePerson")
  24.     @Produces(MediaType.APPLICATION_JSON)
  25.     public JsonResp savePerson(Person person) {
  26.         if (personService.isExistPersonName(person)) {
  27.             return JsonResp.fail("用户名已存在!");
  28.         }
  29.         if (personService.savePerson(person).getId() > 0) {
  30.             return JsonResp.success();
  31.         }
  32.         return JsonResp.fail("系统错误!");
  33.     }
  34. }
复制代码
6、通过postman工具来测试缓存是否生效

第一次访问查找用户:
g1.png
g2.png

第一次通过用户名称来查找用户可以看到是从库中查询的数据,我们可以通过RedisClient工具来查看数据已放入了缓存
g3.png

第二次查找用户:发现服务端并未打印任何数据库查询日志,可以知道第二次查询是从缓存中查询得到的数据。

总结
本文介绍如何通过SpringBoot来一步步集成Redis缓存,关于Redis的使用它不仅可以用作缓存,还可以用来构建队列系统,Pub/Sub实时消息系统,分布式系统的的计数器应用,关于Redis更多的介绍,请前往查阅官方文档。


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP