SpringBoot整合Redis來實現緩存技術

1.概述

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

2.SpringBoot 簡介

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

主要特點:

1. 創建獨立的 Spring 應用程序

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

3. 簡化 Maven 配置

4. 自動配置 Spring

5. 提供生產就緒型功能,如指標,健康檢查和外部配置 6. 絕對沒有代碼生成和對 XML 沒有要求配置

3.Redis 簡介

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

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 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 層應用緩存

@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 e
q null")
public Person savePerson(Person person) {
return personRepo.savePerson(person);
}
/**
* @CacheEvict 應用到刪除數據的方法上,調用方法時會從緩存中刪除對應 key 的數據
*/
@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 數據訪問資源類

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

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

第一次訪問查找用戶:
第一次通過用戶名稱來查找用戶可以看到是從庫中查詢的數據,我們可以通過RedisClient 工具來查看數據已放入了緩存
第二次查找用戶:發現服務端並未打印任何數據庫查詢日誌,可以知道第二次查詢是從緩存中查詢得到的數據。
總結
本文介紹如何通過 SpringBoot 來一步步集成 Redis 緩存,關於 Redis 的使用它不僅可以用作緩存,還可以用來構建隊列系統,Pub/Sub 實時消息系統,分佈式系統的的計數器應用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章