使用 Spring Data Redis 實現 Redis 數據存儲詳解

使用 Spring Data Redis 實現 Redis 數據存儲詳解

Spring Data Redis 是 Spring 生態中操作 Redis 的核心模塊,它封裝了 Redis 客戶端的底層細節(如 Jedis 或 Lettuce),提供了統一的 API 來操作 Redis 的數據結構。以下是詳細實現步驟:


一、配置 Spring Data Redis

1. 引入依賴

pom.xml 中添加依賴(以 Spring Boot 3.x 為例):

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 使用 Lettuce 客戶端(默認) -->
<dependency><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId>
</dependency>
<!-- 可選:連接池(如使用 Jedis) -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>
2. 配置 Redis 連接

application.yml 中配置 Redis 服務器信息:

spring:redis:host: localhost      # Redis 服務器地址port: 6379          # 默認端口password: 123456    # 密碼(若無則省略)database: 0         # 默認數據庫索引lettuce:pool:max-active: 8   # 最大連接數max-idle: 4     # 最大空閑連接min-idle: 1     # 最小空閑連接
3. 配置 RedisTemplate

自定義 RedisTemplate 序列化方式(避免二進制亂碼):

@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);// Key 統一使用字符串序列化template.setKeySerializer(RedisSerializer.string());template.setHashKeySerializer(RedisSerializer.string());// Value 統一使用 JSON 序列化Jackson2JsonRedisSerializer<Object> jsonSerializer = new Jackson2JsonRedisSerializer<>(Object.class);template.setValueSerializer(jsonSerializer);template.setHashValueSerializer(jsonSerializer);// 特殊數據結構的 Value 序列化(根據需求覆蓋)// template.setDefaultSerializer(jsonSerializer); // 可選:全局默認序列化template.afterPropertiesSet();return template;}
}

二、操作 Redis 數據結構

在這里插入圖片描述

1. String(字符串)
  • 用途:存儲簡單鍵值對(如緩存、計數器)。
  • 核心方法opsForValue()
@Autowired
private RedisTemplate<String, Object> redisTemplate;// 寫入值
redisTemplate.opsForValue().set("user:1:name", "Alice");// 讀取值
String name = (String) redisTemplate.opsForValue().get("user:1:name");// 原子遞增
Long count = redisTemplate.opsForValue().increment("article:100:views");
2. Hash(哈希表)
  • 用途:存儲對象字段(如用戶信息)。
  • 核心方法opsForHash()
// 存儲用戶對象
Map<String, String> user = new HashMap<>();
user.put("name", "Bob");
user.put("age", "25");
redisTemplate.opsForHash().putAll("user:2", user);// 獲取單個字段
String age = (String) redisTemplate.opsForHash().get("user:2", "age");// 更新字段
redisTemplate.opsForHash().put("user:2", "age", "26");// 獲取所有字段
Map<Object, Object> userData = redisTemplate.opsForHash().entries("user:2");
3. List(列表)
  • 用途:實現隊列、棧或消息列表。
  • 核心方法opsForList()
// 左側插入元素
redisTemplate.opsForList().leftPush("task:queue", "task1");// 右側彈出元素(阻塞式)
String task = (String) redisTemplate.opsForList().rightPop("task:queue", 10, TimeUnit.SECONDS);// 獲取列表范圍
List<Object> tasks = redisTemplate.opsForList().range("task:queue", 0, -1);
4. Set(集合)
  • 用途:存儲唯一值(如標簽、共同好友)。
  • 核心方法opsForSet()
// 添加元素
redisTemplate.opsForSet().add("article:100:tags", "tech", "java", "spring");// 判斷元素是否存在
boolean exists = redisTemplate.opsForSet().isMember("article:100:tags", "java");// 求交集
Set<Object> commonTags = redisTemplate.opsForSet().intersect("article:100:tags", "article:101:tags");
5. Sorted Set(有序集合)
  • 用途:排行榜、優先級隊列。
  • 核心方法opsForZSet()
// 添加元素及分數
redisTemplate.opsForZSet().add("leaderboard", "player1", 100.0);
redisTemplate.opsForZSet().add("leaderboard", "player2", 85.5);// 獲取前 10 名
Set<ZSetOperations.TypedTuple<Object>> topPlayers = redisTemplate.opsForZSet().reverseRangeWithScores("leaderboard", 0, 9);// 更新分數
redisTemplate.opsForZSet().incrementScore("leaderboard", "player1", 20.0);
6. HyperLogLog
  • 用途:近似統計獨立用戶數(UV)。
  • 核心方法opsForHyperLogLog()
// 添加元素
redisTemplate.opsForHyperLogLog().add("uv:20231001", "user1", "user2", "user3");// 統計基數
Long uv = redisTemplate.opsForHyperLogLog().size("uv:20231001");
7. Bitmaps
  • 用途:位操作(如用戶簽到)。
  • 核心方法opsForValue().setBit()
// 設置第 5 位為 1(表示用戶 ID=5 已簽到)
redisTemplate.opsForValue().setBit("sign:user:202310", 5, true);// 統計總簽到數
Long count = redisTemplate.execute((RedisCallback<Long>) conn -> conn.bitCount("sign:user:202310".getBytes())
);
8. GEO(地理空間)
  • 用途:附近位置查詢。
  • 核心方法opsForGeo()
// 添加地理位置
redisTemplate.opsForGeo().add("cities", new Point(116.405285, 39.904989), "Beijing");// 查詢距離
Distance distance = redisTemplate.opsForGeo().distance("cities", "Beijing", "Shanghai", Metrics.KILOMETERS);// 附近 100km 內的城市
GeoResults<GeoLocation<Object>> results = redisTemplate.opsForGeo().radius("cities", "Beijing", new Distance(100, Metrics.KILOMETERS));

三、高級功能

1. 事務支持
redisTemplate.execute(new SessionCallback<List<Object>>() {@Overridepublic List<Object> execute(RedisOperations operations) {operations.multi();  // 開啟事務operations.opsForValue().set("key1", "value1");operations.opsForHash().put("hash1", "field", "value");return operations.exec();  // 提交事務}
});
2. 發布訂閱
// 發布消息
redisTemplate.convertAndSend("news", "Breaking news: Spring 6 released!");// 訂閱消息(需定義 MessageListener)
@Bean
public MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {return new MessageListenerAdapter(receiver, "receiveMessage");
}@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory factory,MessageListenerAdapter listener) {RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(factory);container.addMessageListener(listener, new ChannelTopic("news"));return container;
}
3. 管道操作(批量執行)
List<Object> results = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {connection.stringCommands().set("key1".getBytes(), "value1".getBytes());connection.stringCommands().set("key2".getBytes(), "value2".getBytes());return null;
});

四、測試與驗證

1. 注入 RedisTemplate
@SpringBootTest
public class RedisTest {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Testvoid testString() {redisTemplate.opsForValue().set("testKey", "Hello Redis");assertEquals("Hello Redis", redisTemplate.opsForValue().get("testKey"));}
}
2. 檢查 Redis 連接
@Autowired
private RedisConnectionFactory redisConnectionFactory;@Test
void testConnection() {RedisConnection conn = redisConnectionFactory.getConnection();assertTrue(conn.ping().equals("PONG"));conn.close();
}

五、注意事項

  1. 序列化一致性
    確保所有操作的 Key/Value 序列化方式一致,避免出現亂碼或類型錯誤。

  2. 連接泄漏
    使用 @Transactional 或手動關閉連接,避免未釋放的連接耗盡資源。

  3. 數據淘汰策略
    在 Redis 配置中設置 maxmemory-policy(如 allkeys-lru),防止內存溢出。

  4. 集群模式
    若使用 Redis 集群,需在配置中指定所有節點地址:

    spring:redis:cluster:nodes: host1:6379,host2:6379,host3:6379
    

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/81164.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/81164.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/81164.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Qt5與現代OpenGL學習(四)X軸方向旋轉60度

把上面兩張圖像放到D盤1文件夾內&#xff1a; shader.h #ifndef SHADER_H #define SHADER_H#include <QDebug> #include <QOpenGLShader> #include <QOpenGLShaderProgram> #include <QString>class Shader { public:Shader(const QString& verte…

【Machine Learning Q and AI 讀書筆記】- 02 自監督學習

Machine Learning Q and AI 中文譯名 大模型技術30講&#xff0c;主要總結了大模型相關的技術要點&#xff0c;結合學術和工程化&#xff0c;對LLM從業者來說&#xff0c;是一份非常好的學習實踐技術地圖. 本文是Machine Learning Q and AI 讀書筆記的第2篇&#xff0c;對應原…

using var connection = connectionFactory.CreateConnection(); using var 是什么意思

在 .NET 中&#xff0c;??垃圾回收&#xff08;Garbage Collection, GC&#xff09;?? 確實是自動管理內存的機制&#xff0c;但它 ??僅適用于托管資源&#xff08;Managed Resources&#xff09;??&#xff08;如類實例、數組等&#xff09;。然而&#xff0c;對于 ?…

Multicore-TSNE

文章目錄 TSNE使用scikit-learn庫使用Multicore-TSNE庫安裝方法基本使用方法采用不同的距離度量 其他資料 TSNE t-Distributed Stochastic Neighbor Embedding (t-SNE) 是一種高維數據的降維方法&#xff0c;由Laurens van der Maaten和Geoffrey Hinton于2008年提出&#xff0…

SI5338-EVB Usage Guide(LVPECL、LVDS、HCSL、CMOS、SSTL、HSTL)

目錄 1. 簡介 1.1 EVB 介紹 1.2 Si5338 Block Diagram 2. EVB 詳解 2.1 實物圖 2.2 基本配置 2.2.1 Universal Pin 2.2.2 IIC I/F 2.2.3 Input Clocks 2.2.4 Output Frequencies 2.2.5 Output Driver 2.2.6 Freq and Phase Offset 2.2.7 Spread Spectrum 2.2.8 快…

Spring AI應用系列——基于OpenTelemetry實現大模型調用的可觀測性實踐

一、項目背景與目標 在AI應用日益復雜的今天&#xff0c;大模型服務&#xff08;如語言理解和生成&#xff09;的性能監控和問題排查變得尤為關鍵。為了實現對大模型調用鏈路的可觀測性&#xff08;Observability&#xff09;管理&#xff0c;我們基于 Spring Boot Spring AI…

Spyglass:官方Hands-on Training(一)

相關閱讀 Spyglasshttps://blog.csdn.net/weixin_45791458/category_12828934.html?spm1001.2014.3001.5482 本文是對Spyglass Hands-on Training中第一個實驗的翻譯&#xff08;有刪改&#xff09;&#xff0c;Lab文件可以從以下鏈接獲取。Spyglass Hands-on Traininghttps:…

PCB設計工藝規范(三)走線要求

走線要求 1.走線要求2.固定孔、安裝孔、過孔要求3.基準點要求4.絲印要求 1.走線要求 印制板距板邊距離:V-CUT 邊大于 0.75mm&#xff0c;銑槽邊大于0.3mm。為了保證 PCB 加工時不出現露銅的缺陷&#xff0c;要求所有的走線及銅箔距離板邊:V-CUT邊大于 0.75mm&#xff0c;銑槽邊…

抓取工具Charles配置教程(mac電腦+ios手機)

mac電腦上的配置 1. 下載最新版本的Charles 2. 按照以下截圖進行配置 2.1 端口號配置&#xff1a; 2.2 https配置 3. mac端證書配置 4. IOS手機端網絡配置 4.1 先查看電腦上的配置 4.2 配置手機網絡 連接和電腦同一個wifi&#xff0c;然后按照以下截圖進行配置 5. 手機端證書…

【CSS】精通Flex布局(全)

目錄 1. flex布局體驗 1.1 傳統布局 與 flex布局 1.2 初體驗 2. flex布局原理 2.1 布局原理 3. flex布局父項常見屬性 3.1 常見父項屬性 3.2 屬性值 3.3 justify-content 設置主軸上的子元素排列方式 3.4 flex-wrap設置子元素是否換行 3.5 align-items 設置側軸上的…

力扣第447場周賽

這次終于趕上力扣的周賽了, 賽時成績如下(依舊還是三題 )&#xff1a; 1. 統計被覆蓋的建筑 給你一個正整數 n&#xff0c;表示一個 n x n 的城市&#xff0c;同時給定一個二維數組 buildings&#xff0c;其中 buildings[i] [x, y] 表示位于坐標 [x, y] 的一個 唯一 建筑。 如…

AI中常用概念的理解

1. RAG&#xff08;檢索增強生成&#xff09; 通俗理解&#xff1a;就像你寫作業時&#xff0c;先查課本 / 百度找資料&#xff0c;再根據資料寫答案&#xff0c;而不是純靠記憶瞎編。 AI 模型&#xff08;比如 ChatGPT&#xff09;回答問題時&#xff0c;先去 “數據庫 / 互聯…

SQLServer多版本兼容Java方案和數據采集

Maven引入 <dependency><groupId>com.microsoft.sqlserver</groupId><artifactId>sqljdbc4</artifactId><version>4.0</version></dependency><dependency><groupId>net.sourceforge.jtds</groupId><ar…

【每日八股】復習 Redis Day4:線程模型

文章目錄 復習 Redis Day4&#xff1a;線程模型介紹一下 Redis 的線程模型核心線程模型&#xff08;Redis 6.0 之前&#xff09;Redis 6.0 的多線程改進Redis 真的是單線程嗎&#xff1f;Redis 的線程模型剖析 上一篇 Redis 的應用我今天才完成&#xff0c;因此明天一并復習 Re…

樹莓派智能攝像頭實戰指南:基于TensorFlow Lite的端到端AI部署

引言&#xff1a;嵌入式AI的革新力量 在物聯網與人工智能深度融合的今天&#xff0c;樹莓派這一信用卡大小的計算機正在成為邊緣計算的核心載體。本文將手把手教你打造一款基于TensorFlow Lite的低功耗智能監控設備&#xff0c;通過MobileNetV2模型實現實時物體檢測&#xff0…

vs2019編譯occ7.9.0時,出現fatal error C1060: compiler is out of heap space

問題描述 visual studio 2019編譯opencascade 7.9.0時&#xff0c;出現編譯錯誤 fatal error C1060: compiler is out of heap space 解決方案 修改vs2019并行編譯的線程個數&#xff0c;默認是12個&#xff0c;我改成了4個&#xff0c;問題解決 Tools > Project and Sol…

vue跨域問題總結筆記

目錄 一、Websocket跨域問題 1.nginx配置 2.VUE CLI代理 3.env.development配置 4.nginx日志 5.解決 一、解決跨域的幾種常用方法 1.Vue CLI代理 2.JSONP 3.WebSocket 4.NGINX解決跨域問題 6.Java解決跨域 二、Vue跨域問題詳解 1. 什么是跨域 2. 跨域的例子 3.…

數據結構篇:線性表的另一表達—鏈表之單鏈表(下篇)

目錄 1.前言 2.是否使用二級指針 3.插入/刪除 3.1 pos位置前/后插入 3.2 查找函數 3.3 pos位置刪除 3.4 pos位置后面刪除 3.5 函數的銷毀 4.斷言問題 4.1 斷言pphead 4.2 斷言*pphead 5.三個文件的代碼 5.1 頭文件 5.2 具體函數實現 5.3 測試用例 1.前言 之前是講…

完美解決react-native文件直傳阿里云oss問題一

前言 通常情況下&#xff0c;作為前后端分離的項目來說&#xff0c;文件上傳是最尋常的功能之一。雖然每個公司選擇的文件管理云庫各不相同&#xff0c;但實現思路基本一致。我所在公司使用阿里云oss文件管理&#xff0c;之前服務端做了透傳&#xff0c;但是由于每個測試環境的…

5.運輸層

5. 運輸層 1. 概述 第2~4章依次介紹了計算機網絡體系結構中的物理層、數據鏈路層和網絡層&#xff0c;它們共同解決了將主機通過異構網絡互聯起來所面臨的問題&#xff0c;實現了主機到主機的通信然而在計算機網絡中實際進行通信的真正實體&#xff0c;是位于通信兩端主機中的…