From 01ba9dad3e284f390224151b510894a776ec4267 Mon Sep 17 00:00:00 2001
From: zwl <1051256694@qq.com>
Date: 星期一, 17 十一月 2025 08:14:32 +0800
Subject: [PATCH] #
---
src/main/java/com/zy/common/utils/RedisUtil.java | 37 +++++++++++++++++++++++++++++++++++++
1 files changed, 37 insertions(+), 0 deletions(-)
diff --git a/src/main/java/com/zy/common/utils/RedisUtil.java b/src/main/java/com/zy/common/utils/RedisUtil.java
index 95da6dc..197b1d5 100644
--- a/src/main/java/com/zy/common/utils/RedisUtil.java
+++ b/src/main/java/com/zy/common/utils/RedisUtil.java
@@ -1,6 +1,8 @@
package com.zy.common.utils;
+import com.baomidou.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@@ -25,8 +27,30 @@
@Autowired
private RedisTemplate redisTemplate;
+ @Autowired
+ private StringRedisTemplate stringRedisTemplate;
+
+ private static final String LOCK_PREFIX = "lock:";
+ private static final long DEFAULT_EXPIRE_TIME = 10; // 榛樿閿佽繃鏈熸椂闂达紝鍗曚綅涓哄垎閽�
+
public RedisUtil(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
+ }
+
+ /**
+ * Redis鍔犻攣鐨勬搷浣�
+ */
+ public Boolean tryLock(String key) {
+ String redisKey = LOCK_PREFIX + key;
+ return redisTemplate.opsForValue().setIfAbsent(redisKey, "locked", DEFAULT_EXPIRE_TIME, TimeUnit.MINUTES);
+ }
+
+ /**
+ * Redis瑙i攣鐨勬搷浣�
+ */
+ public void unlock(String lockKey) {
+ String redisKey = LOCK_PREFIX + lockKey;
+ redisTemplate.delete(redisKey);
}
/**
@@ -126,6 +150,18 @@
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
+ redisTemplate.execute((RedisCallback<Void>) connection -> null);
+ long start = System.currentTimeMillis();
+ while (System.currentTimeMillis() - start < 10000) {//鏈夋晥鏈�10s
+ Object o = redisTemplate.opsForValue().get(key);
+ if (o == null) {
+ continue;
+ }
+
+ if (o.equals(value)) {
+ break;
+ }
+ }
return true;
} catch (Exception e) {
e.printStackTrace();
@@ -148,6 +184,7 @@
} else {
set(key, value);
}
+ redisTemplate.execute((RedisCallback<Void>) connection -> null);
return true;
} catch (Exception e) {
e.printStackTrace();
--
Gitblit v1.9.1