在咱们的平常项目开发过程当中缓存是无处不在的,由于它能够极大的提升系统的访问速度,关于缓存的框架也种类繁多,今天主要介绍的是使用如今很是流行的NoSQL数据库(Redis)来实现咱们的缓存需求。html
Redis简介node
Redis 是一个开源(BSD许可)的,内存中的数据结构存储系统,它能够用做数据库、缓存和消息中间件,Redis 的优点包括它的速度、支持丰富的数据类型、操做原子性,以及它的通用性。git
案例整合github
本案例是在以前一篇SpringBoot + Mybatis + RESTful的基础上来集成Redis的,因此你们若有什么不明白的地方能够前往https://my.oschina.net/feinik/blog/879266,因为篇幅缘由这里不一一贴出全部的代码,具体完整案例代码能够看这里:https://github.com/AIFEINIK/SpringBoot-Learn/tree/master/spring-boot-redis2,关于Redis如何安装可自行google。redis
一、在Maven pom.xml文件中加入Redis包spring
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${boot.version}</version> </dependency>
二、SpringBoot配置文件中配置Redis链接(YAML方式配置)数据库
spring: application: name: spring-boot-redis redis: host: 192.168.145.132 port: 6379 timeout: 20000 cluster: nodes: 192.168.211.134:7000,192.168.211.134:7001,192.168.211.134:7002 maxRedirects: 6 pool: max-active: 8 min-idle: 0 max-idle: 8 max-wait: -1
解释:本配置采用Redis一主三从的的配置方式来提升缓存的吞吐量缓存
三、Redis配置类数据结构
@Configuration public class RedisConfig { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<Object, Object> template = new RedisTemplate<>(); template.setConnectionFactory(connectionFactory); //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值 Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; } }
解释:SpringBoot提供了对Redis的自动配置功能,在RedisAutoConfiguration中默认为咱们配置了JedisConnectionFactory(客户端链接)、RedisTemplate以及StringRedisTemplate(数据操做模板),其中StringRedisTemplate模板只针对键值对都是字符型的数据进行操做,本示例采用RedisTemplate做为数据操做模板,该模板默认采用JdkSerializationRedisSerializer的二进制数据序列化方式,为了方便演示本示例采用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值,使用StringRedisSerializer来序列化和反序列化redis的key值。app
四、Service层应用缓存(注解方式)
@Service public class PersonService { @Autowired private PersonRepo personRepo; /** * @Cacheable 应用到读取数据的方法上,先从缓存中读取,若是没有再从DB获取数据,而后把数据添加到缓存中 * unless 表示条件表达式成立的话不放入缓存 * @param username * @return */ @Cacheable(value = "user", key = "#root.targetClass + #username", unless = "#result eq null") public Person getPersonByName(String username) { Person person = personRepo.getPersonByName(username); return person; } /** * @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓存 * @param person * @return */ @CachePut(value = "user", key = "#root.targetClass + #result.username", unless = "#person eq null") public Person savePerson(Person person) { return personRepo.savePerson(person); } /** * @CacheEvict 应用到删除数据的方法上,调用方法时会从缓存中删除对应key的数据 * @param username * @return */ @CacheEvict(value = "user", key = "#root.targetClass + #username", condition = "#result eq true") public boolean removePersonByName(String username) { return personRepo.removePersonByName(username) > 0; } public boolean isExistPersonName(Person person) { return personRepo.existPersonName(person) > 0; } }
解释:
一、这里的缓存key为简单的字符串组合,也可根据具体须要实现自定义的Key生成器,而后在注解中使用keyGenerator来引用。
二、Spring Cache提供了一些供咱们使用的SpEL上下文数据,经过#来引用,具体可查看Spring官网:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-spel-context。
五、数据访问资源类
@Component @Path("personMgr") public class PersonMgrResource { @Autowired private PersonService personService; @GET @Path("getPersonByName") @Produces(MediaType.APPLICATION_JSON) public JsonResp getPersonByName(@QueryParam("username") String username) { Person person = personService.getPersonByName(username); return JsonResp.success(person); } @POST @Path("removePersonByName") @Produces(MediaType.APPLICATION_JSON) public JsonResp removePersonByName(@QueryParam("username") String username) { if (personService.removePersonByName(username)) { return JsonResp.success(); } return JsonResp.fail("系统错误!"); } @POST @Path("savePerson") @Produces(MediaType.APPLICATION_JSON) public JsonResp savePerson(Person person) { if (personService.isExistPersonName(person)) { return JsonResp.fail("用户名已存在!"); } if (personService.savePerson(person).getId() > 0) { return JsonResp.success(); } return JsonResp.fail("系统错误!"); } }
六、经过postman工具来测试缓存是否生效
第一次访问查找用户:
第一次经过用户名称来查找用户能够看到是从库中查询的数据,咱们能够经过RedisClient工具来查看数据已放入了缓存
第二次查找用户:发现服务端并未打印任何数据库查询日志,能够知道第二次查询是从缓存中查询获得的数据。
总结
本文介绍如何经过SpringBoot来一步步集成Redis缓存,关于Redis的使用它不只能够用做缓存,还能够用来构建队列系统,Pub/Sub实时消息系统,分布式系统的的计数器应用,关于Redis更多的介绍,请前往查阅官方文档。