【Redisson】redis最佳實踐-RedissonUtils+Caffeine

RedissonUtils - 企業級 Redis 緩存工具庫 - 二級緩存

  • 項目地址: hhttps://gitee.com/chen934298133/redisson-utils
  • 問題反饋: Issues
  • 郵箱: chen934298133@163.com

📖 項目簡介

RedissonUtils 是一個基于 Redisson 的企業級 Redis 緩存工具庫,提供了完整的緩存操作解決方案。該項目采用模塊化設計,將不同類型的緩存操作分離到專門的工具類中,提供了簡潔易用的 API 接口。

? 核心特性

  • 🚀 高性能: 基于 Redisson 客戶端,支持異步操作和連接池
  • 🔧 模塊化設計: 按功能分類的工具類,職責清晰
  • 💾 本地緩存: 集成 Caffeine 本地緩存,減輕 Redis 負擔
  • 🔒 分布式鎖: 完整的分布式鎖解決方案
  • 📊 限流控制: 基于令牌桶的分布式限流
  • 🔄 原子操作: 支持原子計數器和原子值操作
  • 📦 集合操作: 完整的 List、Set、Map 緩存操作
  • 📨 消息隊列: 支持發布訂閱、阻塞隊列、可靠隊列、優先級隊列等
  • 🎯 高級隊列: 支持可靠隊列(RReliableQueue)、優先級隊列(RPriorityQueue)、傳輸隊列(RTransferQueue)、環形緩沖區(RRingBuffer)
  • ? 現代化 API: 使用 Duration 替代過時的 TimeUnit

🏗? 架構設計

RedissonUtils (主入口)
├── RedissonObjectUtils      # 基礎對象緩存操作
├── RedissonCollectionUtils  # 集合類型緩存操作
├── RedissonLockUtils        # 分布式鎖操作
├── RedissonAtomicUtils      # 原子操作
├── RedissonQueueUtils       # 隊列和消息操作
├── RedissonRateLimiterUtils # 限流操作
└── RedissonLocalCacheUtils  # 本地緩存管理

🚀 快速開始

1. 添加依賴

<dependency><groupId>org.nehc.algorithm</groupId><artifactId>redisson-utils</artifactId><version>1.0.0</version>
</dependency>

2. 配置 Redisson

# application.yml
spring:redis:host: localhostport: 6379password: your_passworddatabase: 0

3. 基本使用

// 基礎緩存操作
RedissonObjectUtils.setCacheObject("user", "123", userObject, Duration.ofHours(1));
User user = RedissonObjectUtils.getCacheObject("user", "123");// 分布式鎖
if (RedissonLockUtils.tryLock("order", "123", Duration.ofSeconds(10), Duration.ofMinutes(1))) {try {// 業務邏輯} finally {RedissonLockUtils.unLock("order", "123");}
}// 限流控制
if (RedissonRateLimiterUtils.tryAcquire("api:user:123")) {// 執行業務邏輯
}// 可靠隊列操作
RedissonQueueUtils.addReliableQueueMessage("task_queue", taskMessage);
List<Message> messages = RedissonQueueUtils.pollReliableQueueMessage("task_queue", 5);
RedissonQueueUtils.acknowledgeMessage("task_queue", messageId);// 優先級隊列操作
RedissonQueueUtils.addPriorityQueueElement("priority_queue", priorityTask);
Task task = RedissonQueueUtils.pollPriorityQueueElement("priority_queue");// 環形緩沖區操作
RedissonQueueUtils.setRingBufferCapacity("metrics", 1000);
RedissonQueueUtils.addRingBufferElement("metrics", metricData);

📚 API 文檔

RedissonObjectUtils - 基礎對象操作

📋 查看完整測試用例

方法描述示例
setCacheObject(cacheName, key, value)設置緩存對象setCacheObject("user", "123", user)
setCacheObject(cacheName, key, value, duration)設置帶過期時間的緩存setCacheObject("user", "123", user, Duration.ofHours(1))
getCacheObject(cacheName, key)獲取緩存對象getCacheObject("user", "123")
deleteObject(cacheName, key)刪除緩存對象deleteObject("user", "123")
isExistsObject(cacheName, key)判斷緩存是否存在isExistsObject("user", "123")
expire(cacheName, key, duration)設置過期時間expire("user", "123", Duration.ofHours(2))

RedissonLockUtils - 分布式鎖操作

📋 查看完整測試用例

方法描述示例
tryLock(cacheName, key, waitTime, leaseTime)嘗試獲取鎖tryLock("order", "123", Duration.ofSeconds(5), Duration.ofMinutes(1))
tryLock(cacheName, key, timeoutMills)嘗試獲取鎖(毫秒)tryLock("order", "123", 5000)
unLock(cacheName, key)釋放鎖unLock("order", "123")
isLocked(cacheName, key)判斷是否被鎖定isLocked("order", "123")
forceUnlock(cacheName, key)強制釋放鎖forceUnlock("order", "123")

RedissonRateLimiterUtils - 限流操作

📋 查看完整測試用例

方法描述示例
initRateLimiter(key, rateType, rate, rateInterval)初始化限流器initRateLimiter("api:user", RateType.OVERALL, 100, Duration.ofMinutes(1))
tryAcquire(key)嘗試獲取許可tryAcquire("api:user:123")
tryAcquire(key, permits)嘗試獲取指定數量許可tryAcquire("api:user:123", 5)
availablePermits(key)獲取可用許可數availablePermits("api:user:123")

RedissonAtomicUtils - 原子操作

📋 查看完整測試用例

方法描述示例
setAtomicValue(cacheName, key, value)設置原子值setAtomicValue("counter", "page_view", 1000)
getAtomicValue(cacheName, key)獲取原子值getAtomicValue("counter", "page_view")
incrAtomicValue(cacheName, key)原子遞增incrAtomicValue("counter", "page_view")
decrAtomicValue(cacheName, key)原子遞減decrAtomicValue("counter", "page_view")

RedissonCollectionUtils - 集合操作

📋 查看完整測試用例

List 操作
方法描述示例
setCacheList(cacheName, key, list)設置 List 緩存setCacheList("user", "friends:123", friendsList)
getCacheList(cacheName, key)獲取 List 緩存getCacheList("user", "friends:123")
listRightPush(cacheName, key, value, maxSize)右側添加元素listRightPush("log", "user:123", logEntry, 1000)
Set 操作
方法描述示例
setCacheSet(cacheName, key, set)設置 Set 緩存setCacheSet("user", "tags:123", tagsSet)
getCacheSet(cacheName, key)獲取 Set 緩存getCacheSet("user", "tags:123")
Map 操作
方法描述示例
setCacheMap(cacheName, key, map)設置 Map 緩存setCacheMap("user", "profile:123", profileMap)
getCacheMap(cacheName, key)獲取 Map 緩存getCacheMap("user", "profile:123")
setCacheMapValue(cacheName, key, hKey, value)設置 Map 中的值setCacheMapValue("user", "profile:123", "name", "張三")
getCacheMapValue(cacheName, key, hKey)獲取 Map 中的值getCacheMapValue("user", "profile:123", "name")

RedissonQueueUtils - 隊列和消息操作

📋 查看完整測試用例

基礎隊列操作
方法描述示例
addQueueObject(queueName, data)添加隊列元素addQueueObject("task_queue", taskData)
pollQueueObject(queueName)獲取并移除隊列頭部元素pollQueueObject("task_queue")
publish(channelKey, message)發布消息publish("user:notification", notification)
subscribe(channelKey, clazz, consumer)訂閱消息subscribe("user:notification", Notification.class, this::handleNotification)
可靠隊列 (RReliableQueue) 操作
方法描述示例
getReliableQueue(queueName)獲取可靠隊列實例getReliableQueue("reliable_task_queue")
setReliableQueueConfig(queueName, config)設置可靠隊列配置setReliableQueueConfig("queue", config)
addReliableQueueMessage(queueName, message)添加可靠隊列消息addReliableQueueMessage("queue", message)
pollReliableQueueMessage(queueName, count)批量獲取可靠隊列消息pollReliableQueueMessage("queue", 10)
acknowledgeMessage(queueName, messageId)確認消息處理完成acknowledgeMessage("queue", "msg123")
rejectMessage(queueName, messageId)拒絕消息并移至死信隊列rejectMessage("queue", "msg123")
isReliableQueueEmpty(queueName)檢查可靠隊列是否為空isReliableQueueEmpty("queue")
getReliableQueueSize(queueName)獲取可靠隊列大小getReliableQueueSize("queue")
優先級隊列 (RPriorityQueue) 操作
方法描述示例
getPriorityQueue(queueName)獲取優先級隊列實例getPriorityQueue("priority_task_queue")
addPriorityQueueElement(queueName, element)添加優先級隊列元素addPriorityQueueElement("queue", task)
pollPriorityQueueElement(queueName)獲取并移除最高優先級元素pollPriorityQueueElement("queue")
peekPriorityQueueElement(queueName)查看最高優先級元素peekPriorityQueueElement("queue")
傳輸隊列 (RTransferQueue) 操作
方法描述示例
getTransferQueue(queueName)獲取傳輸隊列實例getTransferQueue("transfer_queue")
transferElement(queueName, element)傳輸元素到等待的消費者transferElement("queue", data)
tryTransferElement(queueName, element)嘗試傳輸元素tryTransferElement("queue", data)
hasWaitingConsumer(queueName)檢查是否有等待的消費者hasWaitingConsumer("queue")
環形緩沖區 (RRingBuffer) 操作
方法描述示例
getRingBuffer(bufferName)獲取環形緩沖區實例getRingBuffer("ring_buffer")
setRingBufferCapacity(bufferName, capacity)設置環形緩沖區容量setRingBufferCapacity("buffer", 1000)
addRingBufferElement(bufferName, element)添加元素到環形緩沖區addRingBufferElement("buffer", data)
getRingBufferCapacity(bufferName)獲取環形緩沖區容量getRingBufferCapacity("buffer")
getRingBufferRemainingCapacity(bufferName)獲取剩余容量getRingBufferRemainingCapacity("buffer")

RedissonLocalCacheUtils - 本地緩存管理

📋 查看完整測試用例

方法描述示例
getOrCreateCache(cacheName, maxSize, expireAfterWrite, expireAfterAccess)創建本地緩存getOrCreateCache("user", 1000, Duration.ofMinutes(30), Duration.ofMinutes(10))
set(key, value)設置本地緩存set("user:123", user)
get(key)獲取本地緩存get("user:123")

🔧 高級配置

緩存域配置

public enum CacheScope {APPLICATION("app"),     // 應用級緩存SESSION("session"),     // 會話級緩存USER("user"),          // 用戶級緩存TEMP("temp");          // 臨時緩存private final String cacheName;
}

本地緩存配置

// 自定義本地緩存配置
Cache<String, Object> customCache = RedissonLocalCacheUtils.getOrCreateCache("custom", 5000,                           // 最大緩存數量Duration.ofMinutes(30),         // 寫入后過期時間Duration.ofMinutes(10)          // 訪問后過期時間
);

🎯 最佳實踐

1. 緩存鍵命名規范

// 推薦的命名方式
RedissonObjectUtils.setCacheObject("user", "profile:123", userProfile);
RedissonObjectUtils.setCacheObject("order", "detail:456", orderDetail);

2. 分布式鎖使用

// 推薦的鎖使用模式
String lockKey = "order:" + orderId;
if (RedissonLockUtils.tryLock("business", lockKey, Duration.ofSeconds(5), Duration.ofMinutes(1))) {try {// 執行需要同步的業務邏輯processOrder(orderId);} finally {RedissonLockUtils.unLock("business", lockKey);}
} else {throw new BusinessException("系統繁忙,請稍后重試");
}

3. 限流配置

// API 限流示例
String rateLimiterKey = "api:" + apiPath + ":" + userId;// 初始化限流器:每分鐘最多 100 次請求
RedissonRateLimiterUtils.initRateLimiter(rateLimiterKey, RateType.OVERALL, 100, Duration.ofMinutes(1)
);// 檢查限流
if (!RedissonRateLimiterUtils.tryAcquire(rateLimiterKey)) {throw new RateLimitException("請求過于頻繁,請稍后重試");
}

4. 緩存過期策略

// 不同類型數據的推薦過期時間
RedissonObjectUtils.setCacheObject("user", "profile:" + userId, userProfile, Duration.ofHours(2));     // 用戶信息
RedissonObjectUtils.setCacheObject("config", "system", systemConfig, Duration.ofMinutes(30));          // 系統配置
RedissonObjectUtils.setCacheObject("temp", "captcha:" + sessionId, captcha, Duration.ofMinutes(5));     // 驗證碼

5. 隊列使用最佳實踐

// 可靠隊列使用示例
String queueName = "order_processing";// 配置可靠隊列
QueueConfigParams config = QueueConfigParams.defaults().maxSize(10000).messageMaxSize(1024 * 1024)  // 1MB.messageExpiration(Duration.ofHours(24)).visibilityTimeout(Duration.ofMinutes(5)).deliveryLimit(3);RedissonQueueUtils.setReliableQueueConfig(queueName, config);// 生產者:添加消息
OrderTask task = new OrderTask(orderId, userId);
RedissonQueueUtils.addReliableQueueMessage(queueName, task);// 消費者:處理消息
List<Message> messages = RedissonQueueUtils.pollReliableQueueMessage(queueName, 10);
for (Message message : messages) {try {// 處理業務邏輯processOrder(message.getPayload());// 確認消息處理完成RedissonQueueUtils.acknowledgeMessage(queueName, message.getId());} catch (Exception e) {// 處理失敗,拒絕消息RedissonQueueUtils.rejectMessage(queueName, message.getId());log.error("處理訂單失敗: {}", message.getId(), e);}
}
// 優先級隊列使用示例
String priorityQueueName = "task_priority_queue";// 添加不同優先級的任務
RedissonQueueUtils.addPriorityQueueElement(priorityQueueName, new PriorityTask("urgent", 1));
RedissonQueueUtils.addPriorityQueueElement(priorityQueueName, new PriorityTask("normal", 5));
RedissonQueueUtils.addPriorityQueueElement(priorityQueueName, new PriorityTask("low", 10));// 按優先級處理任務
PriorityTask task = RedissonQueueUtils.pollPriorityQueueElement(priorityQueueName);
if (task != null) {processTask(task);
}
// 環形緩沖區使用示例
String bufferName = "metrics_buffer";// 設置緩沖區容量
RedissonQueueUtils.setRingBufferCapacity(bufferName, 1000);// 添加指標數據(自動覆蓋舊數據)
Metric metric = new Metric("cpu_usage", 85.5, System.currentTimeMillis());
RedissonQueueUtils.addRingBufferElement(bufferName, metric);// 檢查剩余容量
long remaining = RedissonQueueUtils.getRingBufferRemainingCapacity(bufferName);
log.info("緩沖區剩余容量: {}", remaining);

🔍 監控和調試

緩存統計

// 獲取本地緩存統計信息
CacheStats stats = RedissonLocalCacheUtils.stats();
log.info("緩存命中率: {}", stats.hitRate());
log.info("緩存大小: {}", RedissonLocalCacheUtils.size());

鎖狀態檢查

// 檢查鎖狀態
boolean isLocked = RedissonLockUtils.isLocked("business", lockKey);
boolean isHeldByCurrentThread = RedissonLockUtils.isHeldByCurrentThread("business", lockKey);
long remainTime = RedissonLockUtils.remainTimeToLive("business", lockKey);

📄 許可證

本項目采用 MIT 許可證 - 查看 LICENSE 文件了解詳情。

📞 聯系方式

  • 項目地址: hhttps://gitee.com/chen934298133/redisson-utils
  • 問題反饋: Issues
  • 郵箱: chen934298133@163.com

🙏 致謝

感謝以下開源項目的支持:

  • Redisson - Redis Java 客戶端
  • Caffeine - 高性能本地緩存
  • Spring Boot - 應用框架

? 如果這個項目對你有幫助,請給我們一個 Star!

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

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

相關文章

QT(QTableWidget)

QT6QTableWidget QTableWidget是一種Item Widget組件&#xff0c;它以表格形式和管理數據&#xff0c;表格的每個單元格關聯一個QTableWidgetItem對象&#xff0c;可以設置每個單元格的文字內容、字體、文字顏色、背景色、圖標等&#xff0c;還可以有復選框。每個單元格還可以存…

Sentinel相關記錄

系列文章目錄 draft Sentinel 是阿里巴巴開源的 輕量級服務防護組件&#xff0c;主要用于實現以下功能&#xff1a;流量控制FlowRule&#xff08;Rate Limiting&#xff09;&#xff1a;限制單位時間內的請求量&#xff0c;防止系統過載。 熔斷降級DegradeRule&#xff08;Ci…

2025年滲透測試面試題總結-29(題目+回答)

安全領域各種資源&#xff0c;學習文檔&#xff0c;以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各種好玩的項目及好用的工具&#xff0c;歡迎關注。 目錄 二百四十一、XSS 設置Http-Only如何繞過 二百四十二、XSS攻擊手段分類 二百四十三、高殺軟覆蓋工作組的滲…

如何用Wireshark捕獲當前房間路由器和主機的數據包

一、前期工作 在我的這篇文章中&#xff1a; Wireshark USRP聯合波形捕獲&#xff08;上&#xff09;-CSDN博客 通過192.168.1.103這個主機ip篩選Wireshark捕獲的數據包&#xff0c;認為Source和Direction中至少一個包含192.168.1.103才能代表路由器和主機之間的WiFi信號。 …

深度解析游戲引擎中的相機:視圖矩陣

在現代游戲引擎中&#xff0c;相機系統是不可或缺的一部分。它決定了玩家在游戲中看到的視角和場景。而視圖矩陣作為相機系統的核心組件之一&#xff0c;起到了至關重要的作用。本文將深入探討視圖矩陣的原理、計算方法及其在游戲引擎中的應用。 視圖矩陣的基本概念 視圖矩陣…

96、23種設計模式之原型模式(5/23)

原型模式&#xff08;Prototype Pattern&#xff09;是創建型設計模式的一種&#xff0c;其核心思想是通過復制現有對象&#xff08;原型&#xff09;來創建新對象&#xff0c;而非通過構造函數或工廠方法從頭構建。該模式將對象的創建過程從構造邏輯轉移到復制操作&#xff0c…

【python與生活】如何用Python寫一個簡單的自動整理文件的腳本?

用 Python 寫一個自動整理文件的腳本很簡單&#xff0c;核心思路是&#xff1a;按文件后綴&#xff08;如 .jpg、.pdf&#xff09;將文件分類&#xff0c;移動到對應的文件夾&#xff08;如「圖片」「文檔」&#xff09;中。以下是一個實用的實現方案&#xff0c;新手也能輕松修…

SELinux相關介紹

目錄 1.SELinux 概述 2.SELinux 的執行模式 3.SELinux 的使用 1.SELinux 概述 SELinux&#xff08; Security Enhanced Linux 安全性增強的Linux&#xff09;&#xff0c;由美國國家安全局 NSA&#xff08;National Security Agency&#xff09;開發&#xff0c;構建與 Kernel …

【C語言練習】漢諾塔

一、題目 介紹&#xff1a;漢諾塔&#xff08;Tower of Hanoi&#xff09;&#xff0c;又稱河內塔&#xff0c;是一個源于印度古老傳說的益智玩具。大梵天創造世界的時候做了三根金剛石柱子&#xff0c;在一根柱子上從下往上按照大小順序摞著64片黃金圓盤。大梵天命令婆羅門把圓…

隨機森林實戰:在鳶尾花數據集上與決策樹和邏輯斯蒂回歸進行對比

前言 集成學習通過組合多個模型的優勢&#xff0c;常能獲得比單一模型更優的性能&#xff0c;隨機森林便是其中的典型代表。它基于 Bagging 思想&#xff0c;通過對樣本和特征的雙重隨機采樣&#xff0c;構建多棵決策樹并綜合其結果&#xff0c;在降低過擬合風險的同時&#xf…

(計算機網絡)TCP 三握中第三次 ACK 丟失會發生什么?

在 TCP 的三次握手過程中&#xff0c;如果 第三次 ACK 丟失&#xff0c;TCP 是如何保證連接可靠建立的呢&#xff1f;1?? 場景說明第三次 ACK&#xff1a;客戶端發送給服務器的 ACK&#xff0c;確認服務器的 SYN-ACK。假設該 ACK 在網絡傳輸過程中丟失。2?? 客戶端狀態客戶…

容智Report Agent2.0重磅發布!重新定義企業數據分析AI時代

在數據成為生產要素之一的今天&#xff0c;很多企業依然面臨這樣的困境&#xff1a; 想要一份年度財務分析&#xff0c;財務團隊可能要忙半個月甚至一個月&#xff1b;想查一個業務指標&#xff0c;要先找出在哪個系統&#xff0c;再申請權限、寫SQL、調報表&#xff0c;折騰半…

高階數據結構---ST表

hello大家好&#xff0c;今天是2025年8月23日&#xff0c;我要來給大家分享的是一個高階數據結構---ST表。 一&#xff1a;引入 1.RMQ問題&#xff1a; 對于一個長度為 n 的序列&#xff0c;有 m 次查詢操作&#xff0c;每次查詢為一個區間 [l&#xff0c;r] 的最大值&#…

docker 安裝nacos(vL2.5.0)

查找nacos 的所需的鏡像版本 https://hub.docker.com/r/nacos/nacos-server/tags 拉取你所需的版本&#xff08;我們用v2.5.0&#xff09; docker pull nacos/nacos-server:v2.5.0 注意&#xff1a;因為我們需要掛載外配置文件 直接用volume 掛載目錄 缺少初始文件報錯 我們…

在github上通過dmca數字版權申訴侵權并刪除侵權倉庫

DMCA是什么&#xff1f; 《數字千年版權法案》&#xff08;DMCA&#xff09;為版權所有者&#xff08;包括軟件開發人員&#xff09;創建了一個標準化的流程&#xff0c;要求GitHub刪除侵權內容。您可以在美國版權局的官方網站上找到有關DMCA的更多信息。有關GitHub如何處理DM…

AI安全監控與人才需求的時間悖論(對AI安全模型、AI安全人才需求的一些思考)

當監控者與被監控者都是AI時&#xff0c;誰來監控監控者&#xff1f;這個看似簡單的問題&#xff0c;卻揭示了人工智能安全領域的根本性困境。一、問題的提出&#xff1a;當AI監控AI 隨著大語言模型和生成式AI的快速發展&#xff0c;AI系統在元認知層面的能力越來越強&#xff…

AI模型部署 - 大型語言模型(LLM)推理部署中的實際顯存評估

目錄 第一部分:大型語言模型(LLM)推理顯存占用的核心原理 1.1 顯存占用的主要構成部分 1.2 影響顯存占用的關鍵因素 1.2.1 模型架構:MoE vs. 稠密模型 1.2.2 上下文長度與并發數 1.2.3 部署方式與推理框架 1.2.4 硬件能力 第二部分:顯存占用的精確計算方法 2.1 模…

【大語言模型 16】Transformer三種架構深度對比:選擇最適合你的模型架構

【大語言模型 16】Transformer三種架構深度對比&#xff1a;選擇最適合你的模型架構 關鍵詞&#xff1a;Transformer架構&#xff0c;Encoder-Only&#xff0c;Decoder-Only&#xff0c;Encoder-Decoder&#xff0c;BERT&#xff0c;GPT&#xff0c;T5&#xff0c;模型選擇&…

【LeetCode 熱題 100】31. 下一個排列

Problem: 31. 下一個排列 文章目錄整體思路完整代碼時空復雜度時間復雜度&#xff1a;O(N)空間復雜度&#xff1a;O(1)整體思路 這段代碼旨在解決經典的 “下一個排列” (Next Permutation) 問題。問題要求重新排列一個整數數組&#xff0c;使其變為字典序上的下一個更大的排列…

【Linux 進程】進程程序替換

文章目錄1.進程替換的六個庫函數2.execl1.進程替換的六個庫函數 使用 man 3 execl 進行查詢&#xff0c;3表示 Linux 中的3號手冊&#xff0c;即為庫函數&#xff08;例如C標準庫中的庫函數&#xff0c;printf&#xff0c;malloc&#xff09; man 1: 用戶命令&#xff08;在sh…