From 7b487d4c819bc67021cf224c5042066bf73df1e3 Mon Sep 17 00:00:00 2001
From: nickchange <126672920+nickchange@users.noreply.github.com>
Date: 星期六, 28 十月 2023 17:01:00 +0800
Subject: [PATCH] 10.28。2
---
cloud-server-other/src/main/java/com/dsh/other/util/RedisUtil.java | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++
1 files changed, 52 insertions(+), 0 deletions(-)
diff --git a/cloud-server-other/src/main/java/com/dsh/other/util/RedisUtil.java b/cloud-server-other/src/main/java/com/dsh/other/util/RedisUtil.java
index f84642d..88be661 100644
--- a/cloud-server-other/src/main/java/com/dsh/other/util/RedisUtil.java
+++ b/cloud-server-other/src/main/java/com/dsh/other/util/RedisUtil.java
@@ -21,6 +21,8 @@
@Autowired
private JedisPool jedisPool;
+ private static final int TIMEOUT = 10 * 1000; // 10秒超时时间
+ private static final int SLEEP_TIME = 1000; // 1秒休眠时间
/**
* 向redis中存储字符串没有过期时间
@@ -124,4 +126,54 @@
jedis.close();
}
}
+
+
+ public boolean acquireLock(String key,String value) {
+ Jedis jedis = null;
+ try {
+ jedis = jedisPool.getResource();
+ long start = System.currentTimeMillis();
+ String[] split = key.split(";");
+ for (String s : split) {
+
+ while (true) {
+ // 尝试获取锁
+ String result = jedis.set(s, value, "NX", "PX", TIMEOUT);
+ if ("OK".equals(result)) {
+ return true;
+ }
+ // 超时则返回失败
+ if (System.currentTimeMillis() - start > TIMEOUT) {
+ return false;
+ }
+ // 休眠一段时间后重试
+ Thread.sleep(SLEEP_TIME);
+ }
+ }
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (jedis != null) {
+ jedis.close();
+ }
+ }
+ return false;
+ }
+
+ public void releaseLock(String key) {
+ Jedis jedis = null;
+ try {
+ jedis = jedisPool.getResource();
+ jedis.del(key);
+ } catch (Exception e) {
+ e.printStackTrace();
+ } finally {
+ if (jedis != null) {
+ jedis.close();
+ }
+ }
+ }
+
+
}
--
Gitblit v1.7.1