Commit cb0c15c5 authored by yanzg's avatar yanzg

分布式幂等性判断

parent f03ecbd0
...@@ -17,6 +17,12 @@ ...@@ -17,6 +17,12 @@
<!--<groupId>org.springframework.boot</groupId>--> <!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-data-redis</artifactId>--> <!--<artifactId>spring-boot-starter-data-redis</artifactId>-->
<!--</dependency>--> <!--</dependency>-->
<dependency>
<groupId>com.yanzuoguang</groupId>
<artifactId>yzg-util-base</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.alicp.jetcache</groupId> <groupId>com.alicp.jetcache</groupId>
<artifactId>jetcache-starter-redis-lettuce</artifactId> <artifactId>jetcache-starter-redis-lettuce</artifactId>
......
package com.yanzuoguang.redis;
import com.alicp.jetcache.Cache;
import com.yanzuoguang.util.thread.ThreadHelper;
import java.util.concurrent.TimeUnit;
/**
* 运行函数
*
* @author 颜佐光
*/
public class CacheLock implements Runnable {
/**
* 是否执行标记
*/
private boolean runFlag = false;
/**
* 缓存对象
*/
private Cache cache;
/**
* Redis 锁定时间(秒)
*/
private int lockTime;
/**
* 每次等待时间(毫秒)
*/
private int waitUnitTime;
/**
* 关键字
*/
private String key;
/**
* 执行函数
*/
private final Runnable func;
/**
* 构造函数
*
* @param cache
* @param lockTime
* @param waitUnitTime
* @param key
* @param func
*/
public CacheLock(Cache cache, int lockTime, int waitUnitTime, String key, Runnable func) {
this.cache = cache;
this.lockTime = lockTime;
this.waitUnitTime = waitUnitTime;
this.key = key;
this.func = func;
}
/**
* 开始执行,每个关键字会等待其他关键字执行完成后执行
*/
@Override
public void run() {
// 需要运行的函数
Runnable runnable = new Runnable() {
@Override
public void run() {
CacheLock.this.func.run();
runFlag = true;
}
};
do {
// 开启唯一性锁,防止多人运行同一关键字的函数
cache.tryLockAndRun(key, lockTime, TimeUnit.SECONDS, runnable);
// 假如没有运行,则等待50毫秒后继续运行
if (!runFlag) {
ThreadHelper.sleep(waitUnitTime);
}
} while (!runFlag);
}
/**
* 开始执行,每个关键字会等待其他关键字执行完成后执行
*
* @param cache
* @param lockTime
* @param waitUnitTime
* @param key
* @param func
*/
public static void run(Cache cache, int lockTime, int waitUnitTime, String key, Runnable func) {
CacheLock lock = new CacheLock(cache, lockTime, waitUnitTime, key, func);
lock.run();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment