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
spring : redis : host : localhostport : 6379 password : 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. 限流配置
String rateLimiterKey = "api:" + apiPath + ":" + userId;
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 ) . 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!