最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用Spring Boot框架整合Redis的超詳細(xì)案例教程

 更新時(shí)間:2025年11月17日 09:31:35   作者:q***4652  
本文詳細(xì)介紹了如何在SpringBoot項(xiàng)目中整合Redis,包括依賴配置、連接設(shè)置、基本操作和應(yīng)用案例,通過(guò)整合,可以充分利用SpringBoot和Redis的優(yōu)勢(shì),提升應(yīng)用性能和可擴(kuò)展性,感興趣的朋友跟隨小編一起看看吧

# 為什么選擇Spring Boot與Redis整合?

將Spring Boot與Redis整合可以充分利用兩者的優(yōu)勢(shì),簡(jiǎn)化開(kāi)發(fā)并提升應(yīng)用性能。具體好處包括:

  1. 緩存支持:使用Redis作為緩存層可以極大提高應(yīng)用的響應(yīng)速度和可擴(kuò)展性。
  2. 會(huì)話管理:將用戶會(huì)話存儲(chǔ)在Redis中,可以實(shí)現(xiàn)分布式會(huì)話管理。
  3. 數(shù)據(jù)持久性:Redis的持久化功能可以確保數(shù)據(jù)的可靠性。
  4. 簡(jiǎn)化配置:Spring Boot的自動(dòng)配置和Redis Starter可以簡(jiǎn)化配置工作。

了解了這些基礎(chǔ)知識(shí)后,接下來(lái)將詳細(xì)介紹如何在Spring Boot項(xiàng)目中整合Redis,包括依賴配置、連接設(shè)置、基本操作和應(yīng)用案例。

1. 更新 pom.xml

確保你的項(xiàng)目包含了以下依賴。如果使用 Spring Initializr 已經(jīng)添加了 spring-boot-starter-data-redis,這里就無(wú)需再次添加。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-pool2</artifactId>
    </dependency>
</dependencies>

commons-pool2 是用于 Lettuce 連接池配置的依賴。

2. 配置application.yml

補(bǔ)充:

  • Spring Boot 1.x 和 Spring Boot 2.x 中,spring.redis.host 用于配置 Redis 連接屬性。
  • Spring Boot 3.x 中,spring.redis.host 已經(jīng)棄用。
  • Spring Boot 2.x 開(kāi)始,引入了 spring.data.redis 作為配置 Redis 連接的方式,并且在 Spring Boot 3.x 中也可以使用 spring.data.redis 進(jìn)行配置。

src/main/resources 目錄下,添加 Redis 連接池的配置。

application.yml:

server:
  port: 8080
spring:
  redis:
    host: 127.0.0.1  # 地址
    port: 6379  # 端口號(hào)
    database: 0  # 數(shù)據(jù)庫(kù)索引(默認(rèn)為0)
    timeout: 1800000  # 連接超時(shí)時(shí)間(毫秒)
    lettuce:
      pool:
        max-active: 20  # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)
        max-wait: -1  # 最大阻塞等待時(shí)間(負(fù)數(shù)表示沒(méi)有限制)
        max-idle: 5  # 連接池中最大空閑連接
        min-idle: 0  # 連接池中最小空閑連接

3. 創(chuàng)建 Redis 配置類(lèi)

com.lei.my_redis.config 包中創(chuàng)建或更新 RedisConfig 類(lèi),使用連接池配置 LettuceConnectionFactory

package com.lei.my_redis.config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@EnableCaching  // 開(kāi)啟緩存
@Configuration  // 配置類(lèi)
public class RedisConfig extends CachingConfigurerSupport {
    /**
     * 配置 Redis 連接工廠
     * 意義: LettuceConnectionFactory 是連接 Redis 服務(wù)器的入口,它使用了 Lettuce 客戶端,并且配置了連接池來(lái)提高性能和資源管理
     * @return LettuceConnectionFactory
     */
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        // 配置 Redis 服務(wù)器的連接信息
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName("localhost");
        redisStandaloneConfiguration.setPort(6379);
        // redisStandaloneConfiguration.setPassword("password"); // 取消注釋以設(shè)置密碼
        // 配置連接池
        GenericObjectPoolConfig<Object> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMaxTotal(10);       // 連接池中的最大連接數(shù)
        poolConfig.setMaxIdle(5);         // 連接池中的最大空閑連接數(shù)
        poolConfig.setMinIdle(1);         // 連接池中的最小空閑連接數(shù)
        poolConfig.setMaxWaitMillis(2000); // 連接池獲取連接的最大等待時(shí)間
        // 創(chuàng)建一個(gè)帶有連接池配置的 Lettuce 客戶端配置
        LettucePoolingClientConfiguration lettucePoolingClientConfiguration =
                LettucePoolingClientConfiguration.builder()
                        .poolConfig(poolConfig)
                        .build();
        // 返回帶有連接池配置的 Redis 連接工廠
        return new LettuceConnectionFactory(redisStandaloneConfiguration, lettucePoolingClientConfiguration);
    }
    /**
     * 配置并返回一個(gè) RedisTemplate 實(shí)例,用于執(zhí)行 Redis 操作
     * 意義: RedisTemplate 提供了一種高級(jí)抽象,使得開(kāi)發(fā)者可以通過(guò)模板方法操作 Redis,而無(wú)需直接處理底層的 Redis 命令。
     * 它支持多種 Redis 操作,例如值操作、哈希操作、列表操作等
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        /*
            1.創(chuàng)建 RedisTemplate: 這是 Spring 用于與 Redis 交互的核心類(lèi),簡(jiǎn)化了與 Redis 的交互。
            2.設(shè)置連接工廠: 使用前面定義的 LettuceConnectionFactory。
            3.設(shè)置序列化器: 設(shè)置鍵和值的序列化器,這里使用 StringRedisSerializer 來(lái)將鍵和值序列化為字符串。
         */
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory());  // 設(shè)置連接工廠
        template.setKeySerializer(new StringRedisSerializer());  // 設(shè)置鍵的序列化器
        template.setValueSerializer(new StringRedisSerializer()); // 設(shè)置值的序列化器
        return template;
    }
}

4. Redis 操作類(lèi)

保持 Redis 操作類(lèi)和控制器不變。它們已經(jīng)實(shí)現(xiàn)了基本的 Redis 操作。這里只需更新 RedisService 類(lèi)以支持連接池即可。

package com.lei.my_redis.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
 * RedisService 類(lèi)提供了簡(jiǎn)化的 Redis 操作接口,用于在 Spring Boot 應(yīng)用中存儲(chǔ)和檢索數(shù)據(jù)。
 * 它通過(guò) RedisTemplate 與 Redis 服務(wù)器交互,執(zhí)行常見(jiàn)的操作如設(shè)置值、獲取值、設(shè)置值帶過(guò)期時(shí)間和刪除值。
 */
@Service
public class RedisService {
    /*
        意義: RedisTemplate 是 Spring 提供的一個(gè) Redis 操作模板,它抽象了 Redis 的底層訪問(wèn),
        使開(kāi)發(fā)者可以用 Java 對(duì)象操作 Redis。使用 @Autowired 注解,Spring 自動(dòng)將配置好的 RedisTemplate 注入到 RedisService 類(lèi)中
     */
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    // 作用: 向 Redis 中存儲(chǔ)一個(gè)鍵值對(duì)
    public void setValue(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }
    // 作用: 從 Redis 中獲取指定鍵的值
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }
    // 作用: 向 Redis 中存儲(chǔ)一個(gè)鍵值對(duì),并設(shè)置其過(guò)期時(shí)間
    // timeout 指定時(shí)間量,timeUnit 指定時(shí)間單位
    public void setValueWithExpiry(String key, Object value, long timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }
    // 作用: 從 Redis 中刪除指定鍵及其對(duì)應(yīng)的值
    public void deleteValue(String key) {
        redisTemplate.delete(key);
    }
}

5. 創(chuàng)建控制器

RedisController 類(lèi)的實(shí)現(xiàn)保持不變。

package com.lei.my_redis.controller;
import com.lei.my_redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * RedisController 是一個(gè) REST 控制器類(lèi),用于處理客戶端發(fā)來(lái)的 HTTP 請(qǐng)求,并通過(guò)調(diào)用 RedisService
 * 執(zhí)行 Redis 數(shù)據(jù)操作。它提供了三個(gè) API 端點(diǎn):設(shè)置值、獲取值和刪除值
 * RestController注解作用: 表示這個(gè)類(lèi)是一個(gè) RESTful 控制器,它的所有方法的返回值都會(huì)直接作為 HTTP 響應(yīng)體返回。
 * RestController注解意義: 結(jié)合 @Controller 和 @ResponseBody 的功能,簡(jiǎn)化了返回 JSON 格式數(shù)據(jù)的開(kāi)發(fā)工作。
 */
@RestController
public class RedisController {
    @Autowired
    private RedisService redisService;
    /**
     * 作用: 處理 HTTP POST 請(qǐng)求,設(shè)置 Redis 中的鍵值對(duì)
     * 1.使用 @RequestParam 注解獲取請(qǐng)求參數(shù) key 和 value
     * 2.調(diào)用 redisService.setValue(key, value) 方法,將 key 和 value 存儲(chǔ)到 Redis 中
     * 3.返回一個(gè)簡(jiǎn)單的字符串 "Value set" 作為響應(yīng)
     * 請(qǐng)求:POST /set?key=myKey&value=myValue
     * 響應(yīng):"Value set"
     * RequestParam注解:獲取請(qǐng)求參數(shù): 它從 HTTP 請(qǐng)求中獲取參數(shù),并將這些參數(shù)綁定到控制器方法的參數(shù)上
     */
//    @PostMapping("/set")
    @GetMapping("/set")
    public String setValue(@RequestParam String key, @RequestParam String value) {
        redisService.setValue(key, value);
        return "Value:(" + key + ") set";
    }
    /**
     * 作用: 處理 HTTP GET 請(qǐng)求,從 Redis 中獲取指定鍵的值
     * 1.使用 @RequestParam 注解獲取請(qǐng)求參數(shù) key
     * 2.調(diào)用 redisService.getValue(key) 方法,從 Redis 中獲取 key 對(duì)應(yīng)的值,并將結(jié)果轉(zhuǎn)換為 String 類(lèi)型
     * 3.返回獲取的值
     * 請(qǐng)求:GET /get?key=myKey
     * 響應(yīng):"myValue" // Redis 中對(duì)應(yīng) `myKey` 的值
     */
    @GetMapping("/get")
    public String getValue(@RequestParam String key) {
        return (String) redisService.getValue(key);
    }
    /**
     * 作用: 處理 HTTP POST 請(qǐng)求,刪除 Redis 中指定鍵的值
     * 1.使用 @RequestParam 注解獲取請(qǐng)求參數(shù) key
     * 2.調(diào)用 redisService.deleteValue(key) 方法,從 Redis 中刪除 key 對(duì)應(yīng)的鍵值對(duì)
     * 3.返回一個(gè)簡(jiǎn)單的字符串 "Value deleted" 作為響應(yīng)
     * 請(qǐng)求:POST /delete?key=myKey
     * 響應(yīng):"Value deleted"
     */
//    @PostMapping("/delete")
    @GetMapping("/delete")
    public String deleteValue(@RequestParam String key) {
        redisService.deleteValue(key);
        return "Value:(" + key + ") deleted";
    }
}

6. 啟動(dòng)應(yīng)用程序

SpringBootRedisApplication 主類(lèi)保持不變。

package com.lei.my_redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyRedisApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyRedisApplication.class, args);
    }
}

7. 測(cè)試

啟動(dòng)應(yīng)用程序后,可以選中通過(guò) Postman 或?yàn)g覽器訪問(wèn)以下 URL,驗(yàn)證 Redis 操作是否成功。

  • 設(shè)置值: POST http://localhost:8080/set?key=mykey&value=myvalue
  • 獲取值: GET http://localhost:8080/get?key=mykey
  • 刪除值: POST http://localhost:8080/delete?key=mykey

案例1:設(shè)置值

案例2:獲取值

案例3:刪除值

成功在 Spring Boot 項(xiàng)目中整合了 Redis 并配置了連接池。我們使用連接池可以顯著提高 Redis 操作的性能和資源管理效率。

到此這篇關(guān)于使用Spring Boot框架整合Redis的超詳細(xì)案例教程的文章就介紹到這了,更多相關(guān)Spring Boot整合Redis內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringMVC實(shí)現(xiàn)通過(guò)郵件找回密碼功能

    SpringMVC實(shí)現(xiàn)通過(guò)郵件找回密碼功能

    本篇文章主要介紹的是SpringMVC實(shí)現(xiàn)通過(guò)郵件找回密碼功能,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧。
    2016-10-10
  • SpringBoot整合RabbitMQ及生產(chǎn)全場(chǎng)景高級(jí)特性實(shí)戰(zhàn)

    SpringBoot整合RabbitMQ及生產(chǎn)全場(chǎng)景高級(jí)特性實(shí)戰(zhàn)

    本文主要介紹了SpringBoot整合RabbitMQ及生產(chǎn)全場(chǎng)景高級(jí)特性實(shí)戰(zhàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-10-10
  • Linux環(huán)境下Java調(diào)用Python腳本的常見(jiàn)問(wèn)題解決

    Linux環(huán)境下Java調(diào)用Python腳本的常見(jiàn)問(wèn)題解決

    做一個(gè)項(xiàng)目,需要使用java調(diào)用Python腳本,從開(kāi)始各種錯(cuò)誤到最后調(diào)用成功,所以這篇文章就來(lái)記錄一下,有需要的小伙伴可以參考一下
    2025-06-06
  • 詳解SpringBoot如何自定義Starter

    詳解SpringBoot如何自定義Starter

    Starter是Spring Boot中的一個(gè)非常重要的概念,Starter相當(dāng)于模塊,它能將模塊所需的依賴整合起來(lái)并對(duì)模塊內(nèi)的Bean根據(jù)環(huán)境( 條件)進(jìn)行自動(dòng)配置。本文將介紹SpringBoot如何自定義Starter,感興趣的可以學(xué)習(xí)一下
    2021-12-12
  • IDEA java出現(xiàn)無(wú)效的源發(fā)行版14解決方案

    IDEA java出現(xiàn)無(wú)效的源發(fā)行版14解決方案

    這篇文章主要介紹了IDEA java出現(xiàn)無(wú)效的源發(fā)行版14解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • springboot集成spark并使用spark-sql的示例詳解

    springboot集成spark并使用spark-sql的示例詳解

    這篇文章主要介紹了spring-boot集成spark并使用spark-sql的方法,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • java8中Map的一些騷操作總結(jié)

    java8中Map的一些騷操作總結(jié)

    這篇文章主要給大家介紹了關(guān)于java8中Map的一些騷操作,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-02-02
  • 使用Springboot處理跨域的方式

    使用Springboot處理跨域的方式

    這篇文章主要介紹了使用Springboot處理跨域的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-09-09
  • Spring使用@Retryable實(shí)現(xiàn)自動(dòng)重試機(jī)制

    Spring使用@Retryable實(shí)現(xiàn)自動(dòng)重試機(jī)制

    在微服務(wù)架構(gòu)中,服務(wù)之間的調(diào)用可能會(huì)因?yàn)橐恍簳r(shí)性的錯(cuò)誤而失敗,例如網(wǎng)絡(luò)波動(dòng)、數(shù)據(jù)庫(kù)連接超時(shí)或第三方服務(wù)不可用等,在本文中,我們將介紹如何在 Spring 中使用 @Retryable 實(shí)現(xiàn)自動(dòng)重試機(jī)制,需要的朋友可以參考下
    2025-01-01
  • 解決IDEA報(bào)錯(cuò)Failed?to?start?bean‘documentationPluginsBootstrapper‘問(wèn)題

    解決IDEA報(bào)錯(cuò)Failed?to?start?bean‘documentationPluginsBootstra

    這篇文章主要介紹了解決IDEA報(bào)錯(cuò)Failed?to?start?bean‘documentationPluginsBootstrapper‘問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07

最新評(píng)論

康马县| 鹰潭市| 额济纳旗| 武宁县| 钟祥市| 嘉兴市| 永和县| 伊宁县| 伊金霍洛旗| 成武县| 公主岭市| 西丰县| 砚山县| 旬邑县| 田林县| 四川省| 孟连| 海口市| 神木县| 庆安县| 仙游县| 稻城县| 桓仁| 贵州省| 博白县| 日土县| 琼海市| 瑞安市| 得荣县| 永宁县| 珲春市| 马尔康县| 平阴县| 泰州市| 江源县| 武安市| 商南县| 诸暨市| 仙桃市| 蕲春县| 图木舒克市|