Spring Boot 整合 Redis示例代碼步驟詳解
Redis 是一個(gè)高性能的鍵值存儲系統(tǒng),常用于緩存、消息隊(duì)列等多種場景。將 Redis 與 Spring Boot 結(jié)合使用可以極大提升應(yīng)用的性能和響應(yīng)速度。本文將詳細(xì)介紹如何在 Spring Boot 應(yīng)用中整合 Redis,并通過示例代碼展示具體實(shí)現(xiàn)步驟。
1. 引言
隨著互聯(lián)網(wǎng)應(yīng)用對快速讀寫數(shù)據(jù)的需求日益增長,傳統(tǒng)的數(shù)據(jù)庫已經(jīng)難以滿足某些特定場景下的性能要求。Redis 憑借其內(nèi)存級的數(shù)據(jù)訪問速度、豐富的數(shù)據(jù)結(jié)構(gòu)支持以及簡單易用的 API,成為了許多開發(fā)者的首選。接下來,我們將一步步介紹如何在 Spring Boot 中集成 Redis。
2. 添加依賴
首先,在 pom.xml 文件中添加 Spring Data Redis 和 Jedis(或 Lettuce)客戶端的 Maven 依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Spring Boot Starter for Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<!-- Jedis or Lettuce client -->
<!-- Choose one of the following two dependencies -->
<!-- For Jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- Or for Lettuce -->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
</dependencies>3. 配置 Redis 連接信息
接下來,在 application.properties 或 application.yml 文件中配置 Redis 的連接參數(shù)。這里以 .yml 文件為例:
server:
port: 8082
spring:
data:
redis:
host: localhost
port: 6379
password: 1234564. 創(chuàng)建 Redis 操作服務(wù)類
Java實(shí)體
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Description
* @Author HaleyHu
* @Date 2024/12/5 23:41
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String username;
private int age;
}用戶接口類
import org.hbin.redis.entity.User;
/**
* @Description
* @Author HaleyHu
* @Date 2024/12/5 23:44
*/
public interface UserService {
User query(Long id);
Boolean expired(Long id);
}接口實(shí)現(xiàn)類
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.hbin.redis.entity.User;
import org.hbin.redis.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
/**
* @Description
* @Author HaleyHu
* @Date 2024/12/5 23:46
*/
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {
private final RedisTemplate<String, String> redisTemplate;
private final String REDIS_PREFIX_KEY = "User::";
@Override
public User query(Long id) {
Object obj = redisTemplate.opsForValue().get("User::" + id);
if(obj != null) {
return JSON.parseObject(obj.toString(), User.class);
}
// 模擬從DB查詢
User user = new User(id, "user" + id, 20);
redisTemplate.opsForValue().set(REDIS_PREFIX_KEY + id, JSON.toJSONString(user));
return user;
}
@Override
public Boolean expired(Long id) {
return redisTemplate.delete(REDIS_PREFIX_KEY + id);
}
}Controller代碼
import lombok.RequiredArgsConstructor;
import org.hbin.redis.entity.User;
import org.hbin.redis.service.UserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Description
* @Author HaleyHu
* @Date 2024/12/5 23:46
*/
@RequiredArgsConstructor
@RestController
public class UserController {
private final UserService userService;
@GetMapping("/query")
public User query(@RequestParam Long id) {
return userService.query(id);
}
@GetMapping("/expired")
public String expired(@RequestParam Long id) {
return userService.expired(id).toString();
}
}如果你想處理更復(fù)雜的數(shù)據(jù)類型(如對象),則需要使用 RedisTemplate 并配置序列化器。例如,使用 Jackson JSON 序列化器:
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
serializer.setObjectMapper(objectMapper);
template.setValueSerializer(serializer);
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}5. 使用 RedisTemplate 或 ReactiveRedisTemplate
Spring Data Redis 提供了兩種主要的方式來與 Redis 進(jìn)行交互:同步方式 (RedisTemplate) 和響應(yīng)式編程方式 (ReactiveRedisTemplate)。根據(jù)你的需求選擇合適的方式。
同步方式 (RedisTemplate)
這是最常見的方式,適用于大多數(shù)應(yīng)用場景。
響應(yīng)式編程方式 (ReactiveRedisTemplate)
如果你的應(yīng)用采用了響應(yīng)式編程模型(如 WebFlux),那么 ReactiveRedisTemplate 可能更適合你。它允許你以非阻塞的方式與 Redis 進(jìn)行通信。
6. 測試 Redis 功能
最后,我們可以通過編寫單元測試來驗(yàn)證 Redis 的基本功能是否正常工作。也可以部署運(yùn)行上述程序來驗(yàn)證。訪問路徑:http://localhost:8082/query?id=1http://localhost:8082/expired?id=1


7. 注意事項(xiàng)
- 生產(chǎn)環(huán)境配置:在生產(chǎn)環(huán)境中部署時(shí),請確保正確配置 Redis 的安全設(shè)置(如密碼保護(hù)、網(wǎng)絡(luò)限制等),并考慮啟用持久化選項(xiàng)以防止數(shù)據(jù)丟失。
- 性能優(yōu)化:合理調(diào)整連接池參數(shù),避免過多的連接消耗資源;同時(shí)也可以根據(jù)業(yè)務(wù)特點(diǎn)選用合適的序列化器來提高性能。
- 監(jiān)控和維護(hù):定期檢查 Redis 的運(yùn)行狀態(tài),及時(shí)清理過期數(shù)據(jù),保持系統(tǒng)的穩(wěn)定性和高效性。
8. 總結(jié)
通過上述步驟,我們成功地在 Spring Boot 應(yīng)用中集成了 Redis,并實(shí)現(xiàn)了基本的數(shù)據(jù)緩存功能。這不僅提高了應(yīng)用的性能,還為開發(fā)者提供了更多靈活的數(shù)據(jù)管理手段。
到此這篇關(guān)于Spring Boot 整合 Redis示例代碼步驟詳解的文章就介紹到這了,更多相關(guān)Spring Boot 整合 Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot整合Redis實(shí)現(xiàn)訂單超時(shí)自動(dòng)刪除功能
- Springboot整合Redis主從實(shí)踐
- SpringBoot整合Redis實(shí)現(xiàn)序列化的7種策略詳解
- SpringBoot整合redis實(shí)現(xiàn)計(jì)數(shù)器限流的示例
- SpringBoot整合Redisson實(shí)現(xiàn)高性能實(shí)時(shí)排行榜
- springboot整合redisson實(shí)現(xiàn)延時(shí)隊(duì)列(附倉庫地址)
- SpringBoot整合Redis的哨兵模式的實(shí)現(xiàn)
- SpringBoot整合Redisson的兩種方式
相關(guān)文章
MyBatisPlus數(shù)據(jù)權(quán)限控制實(shí)現(xiàn)的三種方式
數(shù)據(jù)權(quán)限是保障數(shù)據(jù)安全的重要手段,本文主要介紹了MyBatisPlus數(shù)據(jù)權(quán)限控制實(shí)現(xiàn)的三種方式,具有一定的參考價(jià)值,具有一定的參考價(jià)值,感興趣的可以了解一下2024-05-05
SpringBoot啟動(dòng)后自動(dòng)執(zhí)行方法的各種方式對比
這篇文章主要為大家詳細(xì)介紹了SpringBoot啟動(dòng)后自動(dòng)執(zhí)行方法的各種方式和性能對比,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下2025-04-04
Java實(shí)現(xiàn)創(chuàng)建Zip壓縮包并寫入文件
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)創(chuàng)建Zip壓縮包并寫入文件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01
Spring Boot 項(xiàng)目啟動(dòng)自動(dòng)執(zhí)行方法的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了Spring Boot 項(xiàng)目啟動(dòng)自動(dòng)執(zhí)行方法的兩種實(shí)現(xiàn)方式,幫助大家更好的理解和學(xué)習(xí)使用Spring Boot框架,感興趣的朋友可以了解下2021-05-05
Java基于余弦方法實(shí)現(xiàn)的計(jì)算相似度算法示例
這篇文章主要介紹了Java基于余弦方法實(shí)現(xiàn)的計(jì)算相似度算法,簡單說明了余弦相似性的概念、原理并結(jié)合實(shí)例形式分析了java實(shí)現(xiàn)余弦相似性算法的相關(guān)操作技巧,需要的朋友可以參考下2017-08-08
利用Intellij Idea連接遠(yuǎn)程服務(wù)器實(shí)現(xiàn)遠(yuǎn)程上傳部署功能
大家在使用Intellij Idea開發(fā)程序的時(shí)候,是不是需要部署到遠(yuǎn)程SSH服務(wù)器運(yùn)行呢,當(dāng)然也可以直接在idea軟件內(nèi)容實(shí)現(xiàn)配置部署操作,接下來通過本文給大家分享利用Intellij Idea連接遠(yuǎn)程服務(wù)器實(shí)現(xiàn)遠(yuǎn)程上傳部署功能,感興趣的朋友跟隨小編一起看看吧2021-05-05
MyBatis limit分頁設(shè)置的實(shí)現(xiàn)
這篇文章主要介紹了MyBatis limit分頁設(shè)置的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

