Commit 3968c0a5 by zhouhaibao

[+]分布式锁添加重试机制

1 parent 173ce2f7
package cn.com.glsx.process.modules.controller; package cn.com.glsx.process.modules.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.glsx.plat.core.annotation.ResponseResultBody; import com.glsx.plat.core.annotation.ResponseResultBody;
import cn.com.glsx.process.job.elastic.core.DynamicTaskService;
import cn.com.glsx.process.job.elastic.impl.DynamicJob;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j @Slf4j
@Tag(name = "动态任务(Demo)") @Tag(name = "动态任务(Demo)")
...@@ -22,7 +16,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -22,7 +16,7 @@ import lombok.extern.slf4j.Slf4j;
@ResponseResultBody @ResponseResultBody
public class TestJobController { public class TestJobController {
@Autowired /* *//* @Autowired
private DynamicTaskService dynamicTaskAdd; private DynamicTaskService dynamicTaskAdd;
@GetMapping("/jobtest") @GetMapping("/jobtest")
...@@ -38,12 +32,12 @@ public class TestJobController { ...@@ -38,12 +32,12 @@ public class TestJobController {
public void updatetest(@RequestParam("cron") String cron, @RequestParam("jobName") String jobName) { public void updatetest(@RequestParam("cron") String cron, @RequestParam("jobName") String jobName) {
dynamicTaskAdd.updateJob(jobName, cron); dynamicTaskAdd.updateJob(jobName, cron);
} }*//*
@PostMapping("/jobtestdel") @PostMapping("/jobtestdel")
@Operation(summary = "动态任务删除", description = "动态任务删除") @Operation(summary = "动态任务删除", description = "动态任务删除")
public void deltest(@RequestParam("jobName") String jobName) { public void deltest(@RequestParam("jobName") String jobName) {
dynamicTaskAdd.removeJob(jobName); dynamicTaskAdd.removeJob(jobName);
} }*/
} }
package cn.com.glsx.process.modules.controller; package cn.com.glsx.process.modules.controller;
import com.xxl.job.core.glue.GlueTypeEnum;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -16,6 +17,8 @@ import io.swagger.v3.oas.annotations.Operation; ...@@ -16,6 +17,8 @@ import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag; import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.util.Date;
@Slf4j @Slf4j
@Tag(name = "xxljob动态任务(Demo)") @Tag(name = "xxljob动态任务(Demo)")
@RestController @RestController
...@@ -75,7 +78,6 @@ public class TestXXLJobController { ...@@ -75,7 +78,6 @@ public class TestXXLJobController {
@PostMapping("/findBybusKey") @PostMapping("/findBybusKey")
@Operation(summary = "任务查询", description = "动态任务触发") @Operation(summary = "任务查询", description = "动态任务触发")
public R findBybusKey(@RequestParam("busKey") String busKey) { public R findBybusKey(@RequestParam("busKey") String busKey) {
SopInstLoadJobHandler.initJob();
return R.ok().data(XxlJobUtil.findByBusKey(busKey)); return R.ok().data(XxlJobUtil.findByBusKey(busKey));
} }
} }
...@@ -133,22 +133,20 @@ public class UserDemoService { ...@@ -133,22 +133,20 @@ public class UserDemoService {
} }
public void testRedis(User user) { public void testRedis(User user) {
boolean b = DistributedLockUtils.tryLock(user.getAccount(), 10 * 1000); boolean b = DistributedLockUtils.lock(user.getAccount(), 1 * 1000);
try {
if (b) { if (b) {
try {
aa(user); aa(user);
} else {
// 锁未释放
return;
}
} catch (Exception e) { } catch (Exception e) {
// //
} finally { } finally {
DistributedLockUtils.unlock(user.getAccount()); DistributedLockUtils.unlock(user.getAccount());
} }
} }
}
private void aa(User user) { private void aa(User user) throws InterruptedException {
System.out.println("user"); System.out.println("user");
Thread.sleep(10 * 1000);
} }
} }
package cn.com.glsx.process.redis; package cn.com.glsx.process.redis;
import com.glsx.plat.context.utils.SpringUtils; import com.glsx.plat.context.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@Slf4j
public class DistributedLockUtils { public class DistributedLockUtils {
public static boolean tryLock(String lockKey, long expireTime) { private static final int DEFAULT_RETRY_TIMES = 3;
// 使用Redis的SETNX命令来尝试获取锁 private static final long DEFAULT_RETRY_INTERVAL = 100;
RedisTemplate restRedisTemplate = SpringUtils.getBean("restRedisTemplate"); /**
Boolean result = restRedisTemplate.opsForValue().setIfAbsent(lockKey, "locked", expireTime, TimeUnit.MILLISECONDS); * 分布式锁不重试
return result != null && result; *
* @param key 锁key
* @param expireTime 过期时间
* @return
*/
public static boolean lock(String key, long expireTime) {
RedisTemplate redisTemplate = SpringUtils.getBean("restRedisTemplate");
log.info("锁获取{}", key);
Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, "lock", expireTime, TimeUnit.MILLISECONDS);
log.info("锁获取结果{}", locked);
if (locked != null && locked) {
return true;
}
return false;
}
/**
* 重试分布式锁
*
* @param key 锁key
* @param expireTime 过期时间
* @param retryCount 重试次数
* @param retryTime 重试时间
* @return
*/
public static boolean lock(String key, long expireTime, Integer retryCount, Long retryTime) {
RedisTemplate redisTemplate = SpringUtils.getBean("restRedisTemplate");
log.info("锁获取{}", key);
Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, "lock", expireTime, TimeUnit.MILLISECONDS);
log.info("锁获取结果{}", locked);
if (locked != null && locked) {
return true;
}
if (retryCount != null) {
return retryLock(key, expireTime, retryCount, retryTime);
}
return false;
}
/**
* 重试
*
* @param key 锁key
* @param expireTime 过期时间
* @param retryCount 重试次数
* @param retryTime 重试时间
* @return
*/
private static boolean retryLock(String key, long expireTime, Integer retryCount, Long retryTime) {
if (retryCount == null) {
retryCount = DEFAULT_RETRY_TIMES;
}
if (retryTime == null) {
retryTime = DEFAULT_RETRY_INTERVAL;
}
RedisTemplate redisTemplate = SpringUtils.getBean("restRedisTemplate");
for (int i = 0; i < retryCount; i++) {
try {
Thread.sleep(retryTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, "lock", expireTime, TimeUnit.MILLISECONDS);
if (locked != null && locked) {
return true;
}
}
return false;
} }
public static void unlock(String lockKey) { public static void unlock(String key) {
RedisTemplate restRedisTemplate = SpringUtils.getBean("restRedisTemplate"); RedisTemplate redisTemplate = SpringUtils.getBean("restRedisTemplate");
restRedisTemplate.delete(lockKey); redisTemplate.delete(key);
log.info("锁释放{}", key);
} }
} }
...@@ -77,7 +77,7 @@ public class TestApplication { ...@@ -77,7 +77,7 @@ public class TestApplication {
public void testredis() throws InterruptedException { public void testredis() throws InterruptedException {
//设置并发数量 //设置并发数量
int count = 10; int count = 1;
//线程池准备 //线程池准备
CyclicBarrier cyclicBarrier = new CyclicBarrier(count); CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
ExecutorService executorService = Executors.newFixedThreadPool(count); ExecutorService executorService = Executors.newFixedThreadPool(count);
......
package cn.com.glsx.test.service; package cn.com.glsx.test.service;
import cn.com.glsx.process.job.xxljob.XxlJobInfo;
import cn.com.glsx.process.job.xxljob.XxlJobUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -32,17 +30,5 @@ public class TestSopService { ...@@ -32,17 +30,5 @@ public class TestSopService {
System.out.println(JSONUtil.toJsonStr(sop)); System.out.println(JSONUtil.toJsonStr(sop));
} }
@Test
public void testXXL() {
XxlJobInfo jobInfo = new XxlJobInfo();
jobInfo.setExecutorParam("");
jobInfo.setJobDesc("jobName2");
jobInfo.setAuthor("admin");
jobInfo.setScheduleConf("0 0/8 * * * ?");
jobInfo.setExecutorHandler("demoJobHandler");
jobInfo.setBusKey("28");
String add = XxlJobUtil.add(jobInfo);
log.info("返回结果{}",add);
}
} }
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!