亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

SpringBoot整合Redis

標簽:
Html5

1. 概述

随着互联网技术的发展,对技术要求也越来越高,所以在当期情况下项目的开发中对数据访问的效率也有了很高的要求,所以在项目开发中缓存技术使用的也越来越多,因为它可以极大的提高系统的访问速度,关于缓存的框架也种类繁多,比如 Redis、Ehchahe、JBoss Cache、Voldemort、Cacheonix 等等,今天主要介绍的是使用现在非常流行的 NoSQL 数据库(Redis)来实现我们的缓存需求。

2. SpringBoot 简介

Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目的是用来简化新Spring 应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot 致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

主要特点:

1. 创建独立的 Spring 应用程序

2. 嵌入的 Tomcat,无需部署 WAR 文件

3. 简化 Maven 配置

4. 自动配置 Spring

5. 提供生产就绪型功能,如指标,健康检查和外部配置

6. 绝对没有代码生成和对 XML 没有要求配置

https://img1.sycdn.imooc.com/aefbd6680850e70f12801135.jpg


3. 简介

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

性,以及它的通用性。

4. 下面就是 SpringBoot 整合 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.62port: 6379timeout: 20000 pool:max-active: 8min-idle: 0max-idle: 8max-wait: -1

4.3 Redis 配置类

@Configurationpublic class RedisApplication {@Beanpublic 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 层应用缓存

@Servicepublic class TestService {

@Autowiredprivate 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) >

4.5 数据访问资源类

@Component @Path("personMgr")public class PersonMgrResource {@Autowiredprivate 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("系统错误!");

}

}

5. 通过 postman 工具来测试缓存是否生效

第一次访问查找用户:

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

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

总结

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

来源:老富贵论坛


點擊查看更多內容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學習,寫下你的評論
感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消