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

全國(guó)咨詢(xún)/投訴熱線(xiàn):400-618-4000

SpringBoot整合NoSQL 數(shù)據(jù)庫(kù)(Redis)實(shí)現(xiàn)緩存[java培訓(xùn)]

更新時(shí)間:2020年04月07日17時(shí)50分 來(lái)源:傳智播客 瀏覽次數(shù):

1.概述

隨著互聯(lián)網(wǎng)技術(shù)的發(fā)展,對(duì)技術(shù)要求也越來(lái)越高,所以在當(dāng)期情況下項(xiàng)目的開(kāi)發(fā)中對(duì)數(shù)據(jù)訪(fǎng)問(wèn)的效率也有了很高的要求,所以在項(xiàng)目開(kāi)發(fā)中緩存技術(shù)使用的也越來(lái)越多,因?yàn)樗梢詷O大的提高系統(tǒng)的訪(fǎng)問(wèn)速度,關(guān)于緩存的框架也種類(lèi)繁多,比如 Redis、Ehchahe、JBoss Cache、Voldemort、Cacheonix 等等,今天主要介紹的是使用現(xiàn)在非常流行的 NoSQL 數(shù)據(jù)庫(kù)(Redis)來(lái)實(shí)現(xiàn)我們的緩存需求。推薦了解java培訓(xùn)課程。

2.SpringBoot簡(jiǎn)介

Spring Boot 是由 Pivotal 團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來(lái)簡(jiǎn)化新 Spring 應(yīng)用的初始搭建以及開(kāi)發(fā)過(guò)程。該框架使用了特定的方式來(lái)進(jìn)行配置,從而使開(kāi)發(fā)人員不再需要定義樣板化的配置。通過(guò)這種方式,Spring Boot 致力于在蓬勃發(fā)展的快速應(yīng)用開(kāi)發(fā)領(lǐng)域(rapid application development)成為領(lǐng)導(dǎo)者。

主要特點(diǎn):

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

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

3)簡(jiǎn)化 Maven 配置

4)自動(dòng)配置 Spring

5)提供生產(chǎn)就緒型功能,如指標(biāo),健康檢查和外部配置

6)絕對(duì)沒(méi)有代碼生成和對(duì) XML 沒(méi)有要求配置

3.Redis簡(jiǎn)介

Redis 是一個(gè)開(kāi)源(BSD 許可)的,內(nèi)存中的數(shù)據(jù)結(jié)構(gòu)存儲(chǔ)系統(tǒng),它可以用作數(shù)據(jù)庫(kù)、緩存和消息中間件,Redis 的優(yōu)勢(shì)包括它的速度、支持豐富的數(shù)據(jù)類(lèi)型、操作原子性,以及它的通用性。

4.下面就是 SpringBoot 整合 Redis 具體實(shí)現(xiàn)步驟

4.1 在 Maven的pom.xml文件中加入Redis包

<!—配置 redis 依賴(lài)-->

<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配置類(lèi)

@Configuration

public class RedisApplication {

    @Bean

    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory) {

        RedisTemplate<Object, Object> template = new RedisTemplate<>();

        template.setConnectionFactory(connectionFactory);

        //使用 Jackson2JsonRedisSerializer 來(lái)序列化和反序列化 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 來(lái)序列化和反序列化 redis 的 key 值

         template.setKeySerializer(new StringRedisSerializer());

         template.afterPropertiesSet();

         return template;

    }

}

4.4 Service 層應(yīng)用緩存

@Service

public class TestService {

     @Autowired

     private PersonRepo personRepo;

     /**

     * @Cacheable 應(yīng)用到讀取數(shù)據(jù)的方法上,先從緩存中讀取,如果沒(méi)有再?gòu)?DB 獲取數(shù)據(jù),然后把數(shù)據(jù)添加到緩存中

     * unless 表示條件表達(dá)式成立的話(huà)不放入緩存

     */

     @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)用到寫(xiě)數(shù)據(jù)的方法上,如新增/修改方法,調(diào)用方法時(shí)會(huì)自動(dòng)把相應(yīng)的數(shù)據(jù)放入緩存 

     */

     @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)用方法時(shí)會(huì)從緩存中刪除對(duì)應(yīng) key 的數(shù)據(jù)

     */

     @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 數(shù)據(jù)訪(fǎng)問(wèn)資源類(lèi)

@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)錯(cuò)誤!");

     }

     @POST

     @Path("savePerson")

     @Produces(MediaType.APPLICATION_JSON)

     public JsonResp savePerson(Person person) {

          if (personService.isExistPersonName(person)) {

              return JsonResp.fail("用戶(hù)名已存在!");

         }

         if (personService.savePerson(person).getId() > 0) {

            return JsonResp.success();

         }

          return JsonResp.fail("系統(tǒng)錯(cuò)誤!");

     }

}

5.通過(guò) postman 工具來(lái)測(cè)試緩存是否生效

第一次訪(fǎng)問(wèn)查找用戶(hù):

第一次通過(guò)用戶(hù)名稱(chēng)來(lái)查找用戶(hù)可以看到是從庫(kù)中查詢(xún)的數(shù)據(jù),我們可以通過(guò) RedisClient 工具來(lái)查看數(shù)據(jù)已放入了緩存。

第二次查找用戶(hù):發(fā)現(xiàn)服務(wù)端并未打印任何數(shù)據(jù)庫(kù)查詢(xún)?nèi)罩荆梢灾赖诙尾樵?xún)是從緩存中查詢(xún)得到的數(shù)據(jù)。

總結(jié)

本文介紹如何通過(guò) SpringBoot 來(lái)一步步集成 Redis 緩存,關(guān)于 Redis 的使用它不僅可以用作緩存,還可以用來(lái)構(gòu)建隊(duì)列系統(tǒng),Pub/Sub 實(shí)時(shí)消息系統(tǒng),分布式系統(tǒng)的的計(jì)數(shù)器應(yīng)用,關(guān)于 Redis 更多的介紹,請(qǐng)前往官網(wǎng)查閱。

猜你喜歡

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

0 分享到:
和我們?cè)诰€(xiàn)交談!