SpringBoot整合Redis來實現緩衝技術方案

來源:互聯網
上載者:User

標籤:自動   pre   val   red   depend   使用者名稱   star   out   bat   

概述

在我們的日常項目開發過程中緩衝是無處不在的,因為它可以極大的提高系統的訪問速度,關於緩衝的架構也種類繁多,今天主要介紹的是使用現在非常流行的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包

<!--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配置類

@Configurationpublic 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值。

 

4、Service層應用緩衝(註解方式)

@Servicepublic 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;    }}

解釋:

 

1、這裡的緩衝key為簡單的字串組合,也可根據具體需要實現自訂的Key產生器,然後在註解中使用keyGenerator來引用。

 

2、Spring Cache提供了一些供我們使用的SpEL上下文資料,通過#來引用,具體可查看Spring官網:http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache-spel-context。

 

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("系統錯誤!");    }}

 

6、通過postman工具來測試緩衝是否生效

 

第一次訪問尋找使用者:

 

第一次通過使用者名稱稱來尋找使用者可以看到是從庫中查詢的資料,我們可以通過RedisClient工具來查看資料已放入了緩衝

第二次尋找使用者:探索服務端並未列印任何資料庫查詢日誌,可以知道第二次查詢是從緩衝中查詢得到的資料。

 

總結

本文介紹如何通過SpringBoot來一步步整合Redis緩衝,關於Redis的使用它不僅可以用作緩衝,還可以用來構建隊列系統,Pub/Sub即時訊息系統,分布式系統的的計數器應用,關於Redis更多的介紹,請前往查閱官方文檔。

 

文章來源:https://my.oschina.net/feinik/blog/1023601

SpringBoot整合Redis來實現緩衝技術方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.