SpringBoot 整合 Redis 來實現(xiàn)緩存技術(shù)

1.概述

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

2.SpringBoot 簡介

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

主要特點:

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

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

3. 簡化 Maven 配置

4. 自動配置 Spring

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

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

3.Redis 簡介

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

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

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 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 層應(yīng)用緩存

@Service

public class TestService {

@Autowired

private PersonRepo personRepo;

/**

* @Cacheable 應(yīng)用到讀取數(shù)據(jù)的方法上,先從緩存中讀取,如果沒有再從 DB 獲取數(shù)據(jù),然后

把數(shù)據(jù)添加到緩存中

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

存 */

@CachePut(value = "user", key = "#root.targetClass + #result.username", unless = "#person e

q null")

public Person savePerson(Person person) {

return personRepo.savePerson(person);

}

/**

* @CacheEvict 應(yīng)用到刪除數(shù)據(jù)的方法上,調(diào)用方法時會從緩存中刪除對應(yīng) key 的數(shù)據(jù)

*/

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

}

}

4.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)錯誤!");

}

}

5.通過 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 更多的介紹,請前往官網(wǎng)查閱。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。