随着互联网技术的发展,对技术要求也越来越高,所以在当期情况下项目的开 发中对数据访问的效率也有了很高的要求,所以在项目开发中缓存技术使用的也越 来越多,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,比 如 Redis、Ehchahe、JBoss Cache、Voldemort、Cacheonix 等等,今天主要介绍的 是使用现在非常流行的 NoSQL 数据库(Redis)来实现我们的缓存需求。
Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新 Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从 而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot 致力于在 蓬勃发展的快速应用开发领域(rapid application development)成为领导者。
主要特点:
1. 创建独立的 Spring 应用程序
2. 嵌入的 Tomcat,无需部署 WAR 文件
3. 简化 Maven 配置
4. 自动配置 Spring
5. 提供生产就绪型功能,如指标,健康检查和外部配置 6. 绝对没有代码生成和对 XML 没有要求配置
Redis 是一个开源(BSD 许可)的,内存中的数据结构存储系统,它可以用作数据库、 缓存和消息中间件,Redis 的优势包括它的速度、支持丰富的数据类型、操作原子 性,以及它的通用性。
4.1 在 Maven 的 pom.xml 文件中加入 Redis 包
<!—配置 redis 依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${boot.version}</version> </dependency>
4.2 SpringBoot 配置文件中配置 Redis 连接
spring: application: name: spring-boot-redis redis: host: 192.168.12.62 port: 6379 timeout: 20000 pool: max-active: 8 min-idle: 0 max-idle: 8 max-wait: -1
4.3 Redis 配置类
@Configuration public class RedisApplication { @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFact ory) { 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; } }
4.4 Service 层应用缓存
@Service public class TestService { @Autowired private PersonRepo personRepo; /** * @Cacheable 应用到读取数据的方法上,先从缓存中读取,如果没有再从 DB 获取数据,然后 把数据添加到缓存中 * unless 表示条件表达式成立的话不放入缓存 */ @Cacheable(value = "user", key = "#root.targetClass + #username", unless = "#result eq null") public Person getPersonByName(String username) { Person person = personRepo.getPersonByName(username); return person; } /** * @CachePut 应用到写数据的方法上,如新增/修改方法,调用方法时会自动把相应的数据放入缓 存 */ @CachePut(value = "user", key = "#root.targetClass + #result.username", unless = "#person e q null") public Person savePerson(Person person) { return personRepo.savePerson(person); } /** * @CacheEvict 应用到删除数据的方法上,调用方法时会从缓存中删除对应 key 的数据 */ @CacheEvict(value = "user", key = "#root.targetClass + #username", condition = "#result eq tr ue") public boolean removePersonByName(String username) { return personRepo.removePersonByName(username) > 0; } public boolean isExistPersonName(Person person) { return personRepo.existPersonName(person) > 0; } }
4.5 数据访问资源类
@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("系统错误!"); } }
第一次访问查找用户: 第一次通过用户名称来查找用户可以看到是从库中查询的数据,我们可以通过RedisClient 工具来查看数据已放入了缓存 第二次查找用户:发现服务端并未打印任何数据库查询日志,可以知道第二次查询是从缓存中查询得到的数据。 总结 本文介绍如何通过 SpringBoot 来一步步集成 Redis 缓存,关于 Redis 的使用它不仅可以用作缓存,还可以用来构建队列系统,Pub/Sub 实时消息系统,分布式系统的的计数器应用。