其他分享
首页 > 其他分享> > 周期任务-选举领航者

周期任务-选举领航者

作者:互联网

每隔单位时间执行一次任务,多节点需要同步

 1     @Autowired
 2     RedissonClient redissonClient;
 3 
 4     /**
 5      * 时间分片
 6      */
 7     private final static long INTERVAL = 30_000L;
 8     /**
 9      * 对象名
10      */
11     private final static String BUCKET_NAME = "";
12     /**
13      * 上次时间分片数
14      */
15     private static long lastTotalIntervals = 0;
16     /**
17      * 领航者标识
18      */
19     private static boolean lastProcess = false;
20 
21     /**
22      * 判断本次是否执行操作
23      * 每 INTERVAL << 1 重新选举
24      *
25      * @return TRUE | FALSE
26      */
27     private boolean operateOneInterval() {
28         // 领航者优先一个时间分片,最多两次运行机会
29         long currentTotalIntervals =
30                 ((lastProcess ? INTERVAL : 0L) + System.currentTimeMillis())
31                         / (INTERVAL << 1);
32         // 比较本地分片
33         if (currentTotalIntervals > lastTotalIntervals) {
34             RBucket<Long> oneIntervalBucket = redissonClient.getBucket(BUCKET_NAME);
35             // 比较最新分片
36             Long redisTotalIntervals = oneIntervalBucket.get();
37             if (Objects.isNull(redisTotalIntervals)
38                     || currentTotalIntervals > (lastTotalIntervals = redisTotalIntervals)) {
39                 boolean beforeStatue = lastProcess;
40                 // 选举领航者,更新标识
41                 lastProcess = oneIntervalBucket.compareAndSet(redisTotalIntervals, currentTotalIntervals);
42                 System.out.printf("争抢结果:%b, 节点变更:%b", lastProcess, beforeStatue != lastProcess);
43             }
44         }
45         return lastProcess;
46     }

 

标签:redisTotalIntervals,lastProcess,周期,选举,private,static,领航者,lastTotalIntervals
来源: https://www.cnblogs.com/htsg/p/16459061.html