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

Spring?Boot2?整合連接?Redis的操作方法

 更新時間:2025年02月05日 09:13:23   作者:ChinaRainbowSea  
在Spring?Boot中,通過RedisTemplate可以方便地對Redis進(jìn)行操作,包括設(shè)置和獲取數(shù)據(jù),文章詳細(xì)介紹了如何配置RedisTemplate,創(chuàng)建RedisConfig類進(jìn)行自定義配置,并通過Controller訪問Redis數(shù)據(jù)庫,感興趣的朋友一起看看吧

1.在 springboot 中 , 整合 redis

可以通過 RedisTemplate 完成對 redis 的操作, 包括設(shè)置數(shù)據(jù)/獲取數(shù)據(jù)

比如添加和讀取數(shù)據(jù)

具體整合實現(xiàn):

創(chuàng)建 Maven 項目:

在 pom.xml 文件當(dāng)中導(dǎo)入相關(guān)的 jar 依賴。如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.rainbowsea</groupId>
    <artifactId>redis_springboot</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <!--   說明:   如果這里是 spring-boot-start 就改成如下 spring-boot-start-web-->
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--        redis-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- spring2.X 集成 redis 所需 common-pool-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <!--不要帶版本號,防止沖突-->
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--         json 轉(zhuǎn)換的 jar 包依賴-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.13.2.2</version>
        </dependency>
    </dependencies>
    <!--    插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

在 resources 目錄下創(chuàng)建 application.properties,完成 redis 的基本配置,如下所示:

#Redis 服務(wù)器地址
spring.redis.host=192.168.76.145
#Redis 服務(wù)器連接端口
spring.redis.port=6379
#Redis 如果有密碼,需要配置,  沒有密碼就不要寫
spring.redis.password=rainbowsea
#Redis 數(shù)據(jù)庫索引(默認(rèn)為 0)
spring.redis.database=0
#連接超時時間(毫秒)
spring.redis.timeout=1800000
#連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
spring.redis.lettuce.pool.max-active=20
#最大阻塞等待時間(負(fù)數(shù)表示沒限制)
spring.redis.lettuce.pool.max-wait=-1
#連接池中的最大空閑連接
spring.redis.lettuce.pool.max-idle=5
#連接池中的最小空閑連接
spring.redis.lettuce.pool.min-idle=0

創(chuàng)建/定義一個 Redis 配置類。

  • 這個 Redis 配置類是對要使用 RedisTemplate bean 對象的配置,可以理解成是一個常規(guī)配置。
  • 和我們以前學(xué)過的一個 JdbcTemplate 的設(shè)計理念類似。
  • 如果不是配置,那么 Spring boot 會使用默認(rèn)配置,這個默認(rèn)配置,會出現(xiàn)一些問題,比如:redisTemplate 的 key 序列化等問題,所以通常我們需要配置這個。Redis 配置類.

創(chuàng)建:\redis_springboot\src\main\java\com\rainbowsea\redis\config\ RedisConfig.java 配置類

package com.rainbowsea.redis.config;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.CacheManager;
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.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
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.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@EnableCaching  // 配置開啟緩存
@Configuration // 定義配置類
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template =
                new RedisTemplate<>();
        System.out.println("template=>" + template);
        RedisSerializer<String> redisSerializer =
                new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        // key 序列化方式
        template.setKeySerializer(redisSerializer);
        // value 序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // value hashmap 序列化
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        return template;
    }
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer =
                new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //解決查詢緩存轉(zhuǎn)換異常的問題
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.activateDefaultTyping(
                LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL,
                JsonTypeInfo.As.WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 配置序列化(解決亂碼的問題),過期時間 600 秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(600))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }
}

創(chuàng)建 controller 訪問設(shè)置/獲取到 Redis 數(shù)據(jù)庫當(dāng)中的數(shù)據(jù)。

重點: 我們這里的 RedisTemplate 模板對象,就是已經(jīng)配置好了 Jedis 的連接上 Redis的一個模板,該模板提供了很多,我們操作 Redis 數(shù)據(jù)庫的方法。就和我們前面學(xué)習(xí) MySQL ,操作連接 MySQL 當(dāng)中的 JdbcTemplate 模板是類似的。

如下所示:

package com.rainbowsea.redis.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
    // 裝配 RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;
    // 編寫一個測試方法
    // 演示設(shè)置數(shù)據(jù)和獲取數(shù)據(jù)
    @GetMapping("/t1")
    public String t1() {
        // 設(shè)置值到 redis 當(dāng)中,opsForValue 是操作 string 字符串的
        redisTemplate.opsForValue().set("book", "天龍八部");
        // 從 redis 當(dāng)中獲取值
        String book = (String) redisTemplate.opsForValue().get("book");
        return book;
    }
}

創(chuàng)建場景啟動器。

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

啟動程序run, 打開瀏覽器地址欄上輸入:http://localhost:9090/redisTest/t1 。

**演示:如何操作 List **

package com.rainbowsea.redis.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
    // 裝配 RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;
    // 演示如何操作 list 列表
    @GetMapping("/t2")
    public String t2() {
        // list-存
        redisTemplate.opsForList().leftPush("books", "笑傲江湖");
        redisTemplate.opsForList().leftPush("books", "hello world");
        // list - 取數(shù)據(jù)
        List books = redisTemplate.opsForList().range("books", 0, -1);
        String booksList = "";
        for (Object book : books) {
            System.out.println("book->" + book.toString());
            booksList += book.toString();
        }
        return booksList;
    }
    // 編寫一個測試方法
    // 演示設(shè)置數(shù)據(jù)和獲取數(shù)據(jù)
    @GetMapping("/t1")
    public String t1() {
        // 設(shè)置值到 redis 當(dāng)中,opsForValue 是操作 string 字符串的
        redisTemplate.opsForValue().set("book", "天龍八部");
        // 從 redis 當(dāng)中獲取值
        String book = (String) redisTemplate.opsForValue().get("book");
        return book;
    }
}

演示:如何操作 hash

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
    // 裝配 RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;
    @GetMapping("/t3")
    public String t3() {
        // hash - 存數(shù)據(jù)
        redisTemplate.opsForHash();
        // 操作 Zset 有序集合
        redisTemplate.opsForZSet();
        // 操作 set 集合
        redisTemplate.opsForSet();
        return null;
    }

2. 注意事項和細(xì)節(jié)

如果沒有提供 RedisConfig 配置類 , springboot 會使用默認(rèn)配置 也可以使用。但是會存在問題。比如 redisTemplate 模糊查找 key 數(shù)據(jù)為空。

測試:

這里我們先將 我們配置的 RedisConfig 配置類注釋掉。

編寫一個方法,獲取所有的 key: * ,表示獲取所有的 key

@RestController
@RequestMapping("/redisTest")
public class RedisTestController {
    // 裝配 RedisTemplate
    @Resource
    private RedisTemplate redisTemplate;
    // 編寫一個方法,獲取所有的 key
    @GetMapping("/t3")
    public String t3() {
        Set keys = redisTemplate.keys("*");
        for (Object key : keys) {
            System.out.println("key -->" + key.toString());
        }
        return "OK";
    }
}

**當(dāng)我們將我們的配置的 RedisConfig 類打開,不使用 Spring Boot 默認(rèn)的配置。則不會出現(xiàn)該空的情況。 **

Unrecognized token 'beijing': was expecting ('true', 'false' or 'null')
看報錯,是 jason 轉(zhuǎn)換異常,實際上是因為 redisTemplate 在做數(shù)據(jù)存儲的時候會把存儲的內(nèi)容序列化,所以,redisTemplate 讀取的時候也會反序列化,而在 redis 客戶端 set 的時候并不會做序列化,因此 set 的進(jìn)去的值在用 redisTemplate 讀的時候就會報類 型轉(zhuǎn)換異常了。

演示:

我們在 Redis 命令行客戶端(不通過Java程序的方式),創(chuàng)建 一個 k100的字符串。
然后,我們再通過Java程序獲取到該(Redis命令行客戶端)所創(chuàng)建的 k100 字符串的數(shù)據(jù)。

解決這個 com.fasterxml.jackson.core.JsonParseException 也簡單,既然我們 Resi 命令行客戶端(創(chuàng)建的 對象信息/值)不會被序列化,那我們就不用 Redis 命令行客戶端創(chuàng)建對象了,直接就是。我們想用Java程序當(dāng)中反序化的功能:我們就用 Java程序創(chuàng)建對象/值,同時也用Java程序獲取對象的數(shù)據(jù)。存和取都保持一致,都是在Java程序當(dāng)中即可(因為Java程序創(chuàng)建的對象會自行序列化的)。這里就不演示了,因為我們上述的所有操作都是:Java程序連接 Redis 創(chuàng)建對象,也是Java程序獲取數(shù)據(jù)。都是沒問題的。

3. 最后:

“在這個最后的篇章中,我要表達(dá)我對每一位讀者的感激之情。你們的關(guān)注和回復(fù)是我創(chuàng)作的動力源泉,我從你們身上吸取了無盡的靈感與勇氣。我會將你們的鼓勵留在心底,繼續(xù)在其他的領(lǐng)域奮斗。感謝你們,我們總會在某個時刻再次相遇。”

到此這篇關(guān)于 Spring Boot2 整合連接 Redis的操作方法的文章就介紹到這了,更多相關(guān)Spring Boot2 連接 Redis內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • java:json-path支持fastjson作為JSON解析提供者的技術(shù)實現(xiàn)方式

    java:json-path支持fastjson作為JSON解析提供者的技術(shù)實現(xiàn)方式

    json-path和fastjson都是Java中常用的JSON處理庫,json-path支持多種解析器,而fastjson具有高性能,通過擴展json-path,使其支持fastjson,可以在保持json-path強大功能的同時,享受fastjson的高性能優(yōu)勢
    2025-12-12
  • Java初學(xué)者必會的Map集合及其原理

    Java初學(xué)者必會的Map集合及其原理

    這篇文章主要給大家介紹Map集合及其原理,該集合中的信息是key-value形式,Map集合與Collection集合又有什么不同呢,要想搞清楚以上問題,下面跟著小編一起來看看吧
    2023-06-06
  • Spring?@Transactional事務(wù)失效的原因分析

    Spring?@Transactional事務(wù)失效的原因分析

    一個程序中不可能沒有事務(wù),Spring中,事務(wù)的實現(xiàn)方式分為兩種:編程式事務(wù)和聲明式事務(wù)。日常項目中,我們都會使用聲明式事務(wù)?@Transactional來實現(xiàn)事務(wù),本文來和大家聊聊什么情況會導(dǎo)致@Transactional事務(wù)失效
    2022-09-09
  • Java5種遍歷HashMap數(shù)據(jù)的寫法

    Java5種遍歷HashMap數(shù)據(jù)的寫法

    這篇文章主要介紹了Java5種遍歷HashMap數(shù)據(jù)的寫法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • SpringMVC的SseEmitter實時推送方式

    SpringMVC的SseEmitter實時推送方式

    SseEmitter是SpringMVC提供的一種技術(shù),可以實現(xiàn)服務(wù)端向客戶端實時推送數(shù)據(jù)的功能,在Controller中提供一個接口返回SseEmitter對象,發(fā)送數(shù)據(jù)可以在另一個接口調(diào)用其send方法,SpringBoot已經(jīng)集成此功能
    2026-03-03
  • mybatis-plus判斷參數(shù)是否為空并作為查詢條件詳解

    mybatis-plus判斷參數(shù)是否為空并作為查詢條件詳解

    文章介紹了MyBatis-Plus中判斷參數(shù)是否為空并作為查詢條件的兩種方式:全局配置和單獨判斷,作者分享了自己的經(jīng)驗,希望能對大家有所幫助
    2026-03-03
  • Java實現(xiàn)Twitter的分布式自增ID算法snowflake

    Java實現(xiàn)Twitter的分布式自增ID算法snowflake

    這篇文章主要介紹了Java實現(xiàn)Twitter的分布式自增ID算法snowflake,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • java 實現(xiàn)雙向鏈表實例詳解

    java 實現(xiàn)雙向鏈表實例詳解

    這篇文章主要介紹了java 實現(xiàn)雙向鏈表實例詳解的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • 一文詳解Java的餓漢和懶漢設(shè)計模式

    一文詳解Java的餓漢和懶漢設(shè)計模式

    這篇文章主要為大家詳細(xì)介紹了Java設(shè)計模式中的的餓漢模式和懶漢模式,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Java有一定的幫助,需要的可以參考一下
    2022-12-12
  • SpringBoot中使用Redis對接口進(jìn)行限流的實現(xiàn)

    SpringBoot中使用Redis對接口進(jìn)行限流的實現(xiàn)

    本文將結(jié)合實例代碼,介紹SpringBoot中使用Redis對接口進(jìn)行限流的實現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-07-07

最新評論

秭归县| 景洪市| 庄浪县| 繁峙县| 陈巴尔虎旗| 长宁区| 明水县| 改则县| 汾阳市| 易门县| 互助| 广南县| 阳城县| 大埔县| 庆安县| 开阳县| 舟山市| 上蔡县| 大新县| 阿图什市| 和硕县| 建宁县| 宁河县| 开封市| 大冶市| 荥阳市| 弋阳县| 郯城县| 讷河市| 青铜峡市| 闵行区| 广西| 开远市| 古蔺县| 德清县| 隆子县| 肇东市| 洛隆县| 苍梧县| 敦煌市| 随州市|