詳解SpringBoot集成Redis來實現(xiàn)緩存技術(shù)方案
概述
在我們的日常項目開發(fā)過程中緩存是無處不在的,因為它可以極大的提高系統(tǒng)的訪問速度,關(guān)于緩存的框架也種類繁多,今天主要介紹的是使用現(xiàn)在非常流行的NoSQL數(shù)據(jù)庫(Redis)來實現(xiàn)我們的緩存需求。
Redis簡介
Redis 是一個開源(BSD許可)的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲系統(tǒng),它可以用作數(shù)據(jù)庫、緩存和消息中間件,Redis 的優(yōu)勢包括它的速度、支持豐富的數(shù)據(jù)類型、操作原子性,以及它的通用性。
案例整合
本案例是在之前一篇SpringBoot + Mybatis + RESTful的基礎(chǔ)上來集成Redis的,具體完整案例代碼可以看這里:https://github.com/AIFEINIK/SpringBoot-Learn/tree/master/spring-boot-redis2,關(guān)于Redis如何安裝可自行g(shù)oogle。
1、在Maven pom.xml文件中加入Redis包
<!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>${boot.version}</version> </dependency>
2、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一主三從的的配置方式來提高緩存的吞吐量
3、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(數(shù)據(jù)操作模板),其中StringRedisTemplate模板只針對鍵值對都是字符型的數(shù)據(jù)進行操作,本示例采用RedisTemplate作為數(shù)據(jù)操作模板,該模板默認采用JdkSerializationRedisSerializer的二進制數(shù)據(jù)序列化方式,為了方便演示本示例采用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值,使用StringRedisSerializer來序列化和反序列化redis的key值。
4、Service層應(yīng)用緩存(注解方式)
@Service public class PersonService { @Autowired private PersonRepo personRepo; /** * @Cacheable 應(yīng)用到讀取數(shù)據(jù)的方法上,先從緩存中讀取,如果沒有再從DB獲取數(shù)據(jù),然后把數(shù)據(jù)添加到緩存中 * 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 應(yīng)用到寫數(shù)據(jù)的方法上,如新增/修改方法,調(diào)用方法時會自動把相應(yīng)的數(shù)據(jù)放入緩存 * @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 應(yīng)用到刪除數(shù)據(jù)的方法上,調(diào)用方法時會從緩存中刪除對應(yīng)key的數(shù)據(jù) * @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; } }
解釋:
1、這里的緩存key為簡單的字符串組合,也可根據(jù)具體需要實現(xiàn)自定義的Key生成器,然后在注解中使用keyGenerator來引用。
2、Spring Cache提供了一些供我們使用的SpEL上下文數(shù)據(jù),通過#來引用,具體可查看Spring官網(wǎng):http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-spel-context。
5、數(shù)據(jù)訪問資源類
@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("系統(tǒng)錯誤!"); } @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("系統(tǒng)錯誤!"); } }
6、通過postman工具來測試緩存是否生效
第一次訪問查找用戶:
第一次通過用戶名稱來查找用戶可以看到是從庫中查詢的數(shù)據(jù),我們可以通過RedisClient工具來查看數(shù)據(jù)已放入了緩存
第二次查找用戶:發(fā)現(xiàn)服務(wù)端并未打印任何數(shù)據(jù)庫查詢?nèi)罩荆梢灾赖诙尾樵兪菑木彺嬷胁樵兊玫降臄?shù)據(jù)。
總結(jié)
本文介紹如何通過SpringBoot來一步步集成Redis緩存,關(guān)于Redis的使用它不僅可以用作緩存,還可以用來構(gòu)建隊列系統(tǒng),Pub/Sub實時消息系統(tǒng),分布式系統(tǒng)的的計數(shù)器應(yīng)用,關(guān)于Redis更多的介紹,請前往查閱官方文檔。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中動態(tài)設(shè)置JVM參數(shù)的方法總結(jié)
通過動態(tài)設(shè)置JVM參數(shù),開發(fā)者可以更有效地管理資源使用和優(yōu)化性能,本文將詳細闡述如何在Java中動態(tài)設(shè)置JVM參數(shù),感興趣的小伙伴可以了解下2024-12-12Eclipse如何導(dǎo)入Maven項目詳解(新手初學(xué))
這篇文章主要介紹了Eclipse如何導(dǎo)入Maven項目詳解(新手初學(xué)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法
Spring MVC是個靈活的框架,返回JSON數(shù)據(jù)的也有很多五花八門的方式,這里我們來整理一個最簡單的Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法:2016-05-05使用Springboot封裝一個自適配的數(shù)據(jù)單位轉(zhuǎn)換工具類
我們在接收前臺傳輸?shù)臄?shù)據(jù)時,往往SpringBoot使用內(nèi)置的數(shù)據(jù)類型轉(zhuǎn)換器把我們提交的數(shù)據(jù)自動封裝成對象等類型,下面這篇文章主要給大家介紹了關(guān)于使用Springboot封裝一個自適配的數(shù)據(jù)單位轉(zhuǎn)換工具類的相關(guān)資料,需要的朋友可以參考下2023-03-03