springboot中操作redis

来源:https://www.cnblogs.com/minqiliang/archive/2023/06/18/17489356.html
-Advertisement-
Play Games

## 1.maven引入相關依賴 ~~~xml org.springframework.boot spring-boot-starter-data-redis org.apache.commons commons-pool2 2.11.1 com.fasterxml.jackson.core jac ...


1.maven引入相關依賴

<dependencies>
 	<!-- spring-boot-starter-data-redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!-- commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.11.1</version>
        </dependency>
        <!--jackjson-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>

2.配置redis

application.yml

spring:
  # 配置redis
  redis:
    host: 192.168.***.***
    port: 6379
    password: ******
    lettuce:
      pool:
        max-active: 8 # 連接池最大連接數(使用負值表示沒有限制)
        max-idle: 8 # 連接池中的最大空閑連接
        max-wait: 100 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
        min-idle: 0 # 連接池中的最小空閑連接
    database: 0 # redis資料庫索引(預設為0)

3.配置序列化

package com.example.config;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis  序列化方式配置
 *
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 創建RedisTemplate<String, Object>對象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置連接工廠
        template.setConnectionFactory(factory);
        // json方式序列化對象
        GenericJackson2JsonRedisSerializer jsonRedisSerializer =
                new GenericJackson2JsonRedisSerializer();
        // key採用String的序列化方式
        template.setKeySerializer(RedisSerializer.string());
        // hash的key也採用String的序列化方式
        template.setHashKeySerializer(RedisSerializer.string());
        // value序列化方式採用jackson
        template.setValueSerializer(jsonRedisSerializer);
        // hash的value序列化方式採用jackson
        template.setHashValueSerializer(jsonRedisSerializer);
        return template;
    }

}

4.測試類中進行測試

package com.example;

import com.example.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

@SpringBootTest
class SpringDataRedisTestApplicationTests {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 測試redis的String類型
     */
    @Test
    void testString() {
        redisTemplate.opsForValue().set("name", "minqiliang");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }

    /**
     * 使用StringRedisTemplate操作redis(需要手動進行序列化和反序列化)
     * @throws JsonProcessingException
     */
    @Test
    void testString2() throws JsonProcessingException {
        // 創建一個對象
        User user = new User("001", "minqiliang", 18);
        // 由於StringRedisTemplate預設使用的是String的序列化器,所以這裡需要將對象轉換成json字元串
        String json = objectMapper.writeValueAsString(user);
        // 存入redis
        stringRedisTemplate.opsForValue().set("user:001", json);
        // 從redis中取出數據
        String s = stringRedisTemplate.opsForValue().get("user:001");
        // 將json字元串轉換成對象
        User u = objectMapper.readValue(s, User.class);
        System.out.println(u);
    }

    @Test
    void testHash() {
        // 存入redis
        redisTemplate.opsForHash().put("user:002", "id", "002");
        redisTemplate.opsForHash().put("user:002", "name", "張三");
        redisTemplate.opsForHash().put("user:002", "age", 18);
        // 獲取對應的key的所有值
        System.out.println(redisTemplate.opsForHash().entries("user:002"));
        System.out.println("====================================");
        // 獲取對應的key的某個值
        System.out.println(redisTemplate.opsForHash().get("user:002", "id"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "name"));
        System.out.println(redisTemplate.opsForHash().get("user:002", "age"));
    }
}

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文主要介紹在之家廣告業務系統中運用任務編排治理工具的場景及其可以解決的問題,講解任務編排框架的核心要點,以及向大家演示一個任務編排框架的基本結構,讓大家對任務編排工具增強業務開發效率,提高研發質量有更深刻的理解。 ...
  • # Go 語言之 zap 日誌庫簡單使用 ## 預設的 Go log log:https://pkg.go.dev/log ```go package main import ( "log" "os" ) func init() { log.SetPrefix("LOG: ") // 設置首碼 f, ...
  • ## 前言 使用 ABP vNext(下文簡稱 ABP)時,通常都是從 cli 開始新建模板,從一個空項目開始。對已經存續的項目來說,現有的數據,特別是用戶等核心數據需要進行遷移。 老的項目,隨著規模越來越大,每次修改都需要更改非常多地方,最重要的是,共用資料庫使得維護起來需要小心翼翼。為了後續維護 ...
  • 經過前幾篇文章的講解,初步瞭解ASP.NET Core MVC項目創建,啟動運行,以及命名約定,創建控制器,視圖,模型,接收參數,傳遞數據ViewData,ViewBag,路由,頁面佈局,wwwroot和客戶端庫,Razor語法,EnityFrameworkCore與資料庫,HttpContext,... ...
  • # 個人博客文章歸檔實現📑 # 前言 隨著博客的文章越來越多,那麼歸檔就顯得尤為重要,然後最近也是沒什麼課,加緊更新一下博客,之前也是更新了評論、留言板。 然後博客是使用的前後的不分離的項目,數據返回一般都是用的.NET的強類型數據返回,也會用到分佈視圖。 重點是一段sql查詢困惱我許久,在後端接 ...
  • 大家好,我是 god23bin。歡迎來到《一分鐘學一個 Linux 命令》系列,每天只需一分鐘,記住一個 Linux 命令不成問題。今天要說的是 ps 命令。 ...
  • MySQL作為一個流行的開源關係型資料庫管理系統,它可以運行在多種平臺上,支持多種存儲引擎,提供了靈活的數據操作和管理功能。 ...
  • Mysql8社區版日誌審計插件 過去從Mysql官方自帶general.log日誌的相比其他插件性能是最差的,我們考慮參考行業中較好的插件是MariaDB Audit Plugin, 可惜並不相容mysql 5.7與mysql 8.0以上版本。亞馬遜RDS for MySQL的開發團隊已經folk了 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...