java分布式保证幂等性_分布式环境保证定时任务的幂等性

@Component

public class RegularTask {

private static final Logger log = LoggerFactory.getLogger(RegularTask.class);

private static final String ZOOKEEPER_STR = "10.25.142.55:2181,10.48.24.36:2181";

private static CuratorFramework curatorFramework;

private static LeaderLatch leaderLatch;

static {

RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

curatorFramework = CuratorFrameworkFactory.newClient(ZOOKEEPER_STR, retryPolicy);

curatorFramework.start();

leaderLatch = new LeaderLatch(curatorFramework, "/regulartask");

try {

leaderLatch.start();

} catch (Exception e) {

log.error("LeaderLatch start error:{}", e);

}

}

@Lazy

@Scheduled(cron = "")

public void send() {

try {

if (!leaderLatch.hasLeadership()) {

log.info("current mechine is not a leader");

return;

}

//TODO 定时任务逻辑

} catch (Exception e) {

log.error("regulartask run error:{}", e);

} finally {

try {

if (leaderLatch != null) {

leaderLatch.close();

}

} catch (IOException e) {

log.error("leaderLatch close error:{}", e);

e.printStackTrace();

}

}

}

}

你可能感兴趣的:(java分布式保证幂等性)