干燥机配套车间生产管理系统/云平台服务端
baoshiwei
2024-12-11 7c585586e9bea943161676bd9d127e81123891c3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package org.jeecg.modules.test.lock;
 
import lombok.extern.slf4j.Slf4j;
import org.jeecg.boot.starter.lock.annotation.JLock;
import org.jeecg.boot.starter.lock.client.RedissonLockClient;
import org.jeecg.modules.test.constant.CloudConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
import java.util.Map;
 
/**
 * 分布式锁测试demo
 * @author: zyf
 * @date: 2022/04/21
 */
@Slf4j
@Component
public class DemoLockTest {
    @Autowired
    RedissonLockClient redissonLock;
//    @Autowired
//    RabbitMqClient rabbitMqClient;
 
    /**
     * 测试方法:
     *    @Scheduled(cron = "0/5 * * * * ?") 表示每5秒执行一次
     *    @JLock(lockKey = CloudConstant.REDISSON_DEMO_LOCK_KEY1)分布式锁,10秒钟才释放
     *    结果:每10秒钟输出一次 “执行 分布式锁 业务逻辑1” 就说明锁成功了
     *
     * 测试分布式锁【注解方式】
     */
    @Scheduled(cron = "0/5 * * * * ?")
    @JLock(lockKey = CloudConstant.REDISSON_DEMO_LOCK_KEY1)
    public void execute() throws InterruptedException {
        log.info("执行execute任务开始,休眠十秒开始,当前系统时间戳(秒):"+ System.currentTimeMillis()/1000);
        Thread.sleep(10000);
        log.info("========执行 分布式锁 业务逻辑1=============");
//        Map map = new BaseMap();
//        map.put("orderId", "BJ0001");
//        rabbitMqClient.sendMessage(CloudConstant.MQ_JEECG_PLACE_ORDER, map);
//        //延迟10秒发送
//        map.put("orderId", "NJ0002");
//        rabbitMqClient.sendMessage(CloudConstant.MQ_JEECG_PLACE_ORDER, map, 10000);
 
        log.info("execute任务结束,休眠十秒完成,当前系统时间戳(秒):"+ System.currentTimeMillis()/1000);
    }
 
 
    /**
     * 测试分布式锁【编码方式】
     * @Scheduled(cron = "0/5 * * * * ?")
     */
    public void execute2() throws InterruptedException {
        int expireSeconds=6000;
        if (redissonLock.tryLock(CloudConstant.REDISSON_DEMO_LOCK_KEY2, -1, expireSeconds)) {
            log.info("执行任务execute2开始,休眠十秒");
            Thread.sleep(10000);
           log.info("=============业务逻辑2===================");
            log.info("定时execute2结束,休眠十秒");
 
            redissonLock.unlock(CloudConstant.REDISSON_DEMO_LOCK_KEY2);
        } else {
            log.info("execute2获取锁失败");
        }
    }
 
}