教育行業(yè)A股IPO第一股(股票代碼 003032)

全國咨詢/投訴熱線:400-618-4000

SpringBoot整合NoSQL 數據庫(Redis)實現緩存[java培訓]

更新時間:2020年04月07日17時50分 來源:傳智播客 瀏覽次數:

1.概述

隨著互聯網技術的發(fā)展,對技術要求也越來越高,所以在當期情況下項目的開發(fā)中對數據訪問的效率也有了很高的要求,所以在項目開發(fā)中緩存技術使用的也越來越多,因為它可以極大的提高系統(tǒng)的訪問速度,關于緩存的框架也種類繁多,比如 Redis、Ehchahe、JBoss Cache、Voldemort、Cacheonix 等等,今天主要介紹的是使用現在非常流行的 NoSQL 數據庫(Redis)來實現我們的緩存需求。推薦了解java培訓課程

2.SpringBoot簡介

Spring Boot 是由 Pivotal 團隊提供的全新框架,其設計目的是用來簡化新 Spring 應用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進行配置,從而使開發(fā)人員不再需要定義樣板化的配置。通過這種方式,Spring Boot 致力于在蓬勃發(fā)展的快速應用開發(fā)領域(rapid application development)成為領導者。

主要特點:

1)創(chuàng)建獨立的 Spring 應用程序

2)嵌入的 Tomcat,無需部署 WAR 文件

3)簡化 Maven 配置

4)自動配置 Spring

5)提供生產就緒型功能,如指標,健康檢查和外部配置

6)絕對沒有代碼生成和對 XML 沒有要求配置

3.Redis簡介

Redis 是一個開源(BSD 許可)的,內存中的數據結構存儲系統(tǒng),它可以用作數據庫、緩存和消息中間件,Redis 的優(yōu)勢包括它的速度、支持豐富的數據類型、操作原子性,以及它的通用性。

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.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 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;

    }

}

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 eq null")

     public Person savePerson(Person person) {

          return personRepo.savePerson(person);

     }

     /**

     * @CacheEvict 應用到刪除數據的方法上,調用方法時會從緩存中刪除對應 key 的數據

     */

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

     }

}

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

     }

}

5.通過 postman 工具來測試緩存是否生效

第一次訪問查找用戶:

第一次通過用戶名稱來查找用戶可以看到是從庫中查詢的數據,我們可以通過 RedisClient 工具來查看數據已放入了緩存。

第二次查找用戶:發(fā)現服務端并未打印任何數據庫查詢日志,可以知道第二次查詢是從緩存中查詢得到的數據。

總結

本文介紹如何通過 SpringBoot 來一步步集成 Redis 緩存,關于 Redis 的使用它不僅可以用作緩存,還可以用來構建隊列系統(tǒng),Pub/Sub 實時消息系統(tǒng),分布式系統(tǒng)的的計數器應用,關于 Redis 更多的介紹,請前往官網查閱。

猜你喜歡

什么是java四大引用?Java引用介紹

0 分享到:
和我們在線交談!