zk保证定时任务集群部署时单个节点执行

@Component
public class ZKLeaderLatch {

    private static CuratorFramework zkClient;
    private static LeaderLatch leaderLatch;


    public ZKLeaderLatch(@Value("${zkservers}")String servers, @Value("${masterkey}")String masterkey) {
        String connectString = servers;
        String masterKey = masterkey;
        try {
            final String zkid = String.format("zkLatchClient#%s", InetAddress.getLocalHost().getHostAddress());
            CommonLogger.printInfo(this,"zk "+zkid+" client init... server:"+connectString+", masterKey:"+masterKey+"");
            RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
            zkClient = CuratorFrameworkFactory.builder().connectString(connectString)
                    .sessionTimeoutMs(6000).retryPolicy(retryPolicy).build();
            CommonLogger.printInfo(this,"zk client start....");
            zkClient.start();
            leaderLatch = new LeaderLatch(zkClient, masterKey,zkid);
            LeaderLatchListener leaderLatchListener = new LeaderLatchListener() {
                @Override
                public void notLeader() {
                    CommonLogger.printInfo(this,"client "+zkid+" is not main. ");
                }
                @Override
                public void isLeader() {
                    CommonLogger.printInfo(this,"client "+zkid+" is main. YEAH!");
                }
            };
            leaderLatch.addListener(leaderLatchListener);
            CommonLogger.printInfo(this,"leaderLatch start....");

            leaderLatch.start();
        } catch(Exception e) {
            CommonLogger.printInfo(this,"client err. "+e.getMessage(),e);
        }
    }


    public boolean isLeader() {
        return leaderLatch.hasLeadership();
    }

    public CuratorFramework getClient(){
        return zkClient;
    }

    public LeaderLatch getLatch(){
        return leaderLatch;
    }
}
配置依赖

            org.apache.curator
            curator-framework
            4.0.1
        

        
            org.apache.curator
            curator-recipes
            4.1.0
        

        
            org.apache.curator
            curator-client
            4.0.1
        

        
        
            org.apache.zookeeper
            zookeeper
            3.4.9
            
                
                    org.slf4j
                    slf4j-log4j12
                
            
        

你可能感兴趣的:(zk保证定时任务集群部署时单个节点执行)