Spring Boot 整合 Redis示例代碼步驟詳解
Redis 是一個(gè)高性能的鍵值存儲(chǔ)系統(tǒng),常用于緩存、消息隊(duì)列等多種場(chǎng)景。將 Redis 與 Spring Boot 結(jié)合使用可以極大提升應(yīng)用的性能和響應(yīng)速度。本文將詳細(xì)介紹如何在 Spring Boot 應(yīng)用中整合 Redis,并通過示例代碼展示具體實(shí)現(xiàn)步驟。
1. 引言
隨著互聯(lián)網(wǎng)應(yīng)用對(duì)快速讀寫數(shù)據(jù)的需求日益增長(zhǎng),傳統(tǒng)的數(shù)據(jù)庫(kù)已經(jīng)難以滿足某些特定場(chǎng)景下的性能要求。Redis 憑借其內(nèi)存級(jí)的數(shù)據(jù)訪問速度、豐富的數(shù)據(jù)結(jié)構(gòu)支持以及簡(jiǎn)單易用的 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ù)類型(如對(duì)象),則需要使用 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)用場(chǎng)景。
響應(yīng)式編程方式 (ReactiveRedisTemplate)
如果你的應(yīng)用采用了響應(yīng)式編程模型(如 WebFlux),那么 ReactiveRedisTemplate 可能更適合你。它允許你以非阻塞的方式與 Redis 進(jìn)行通信。
6. 測(cè)試 Redis 功能
最后,我們可以通過編寫單元測(cè)試來驗(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í),請(qǐng)確保正確配置 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)容請(qǐng)搜索腳本之家以前的文章或繼續(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ì)列(附倉(cāng)庫(kù)地址)
- SpringBoot整合Redis的哨兵模式的實(shí)現(xiàn)
- SpringBoot整合Redisson的兩種方式
相關(guān)文章
Bean實(shí)例化之前修改BeanDefinition示例詳解
這篇文章主要為大家介紹了Bean實(shí)例化之前修改BeanDefinition示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12
SpringSecurity oAuth2.0的四種模式(小結(jié))
本文主要介紹了SpringSecurity oAuth2.0的四種模式,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
Java 本地方法Native Method詳細(xì)介紹
這篇文章主要介紹了 Java 本地方法Native Method詳細(xì)介紹的相關(guān)資料,需要的朋友可以參考下2017-02-02
java 自己實(shí)現(xiàn)DataSource實(shí)現(xiàn)實(shí)例
這篇文章主要介紹了java 自己實(shí)現(xiàn)DataSource實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-05-05

