Curator教程:https://www.jianshu.com/p/70151fc0ef5d
Curator包含了几个包:
- curator-framework:对zookeeper的底层api的一些封装
- curator-client:提供一些客户端的操作,例如重试策略等
- curator-recipes:封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式计数器、分布式Barrier等
spring:
application:
name: zookeeper
zookeeper:
server: 127.0.0.1:2181
znode: /kexin_zookeeper/test
client_id: zk_client
package com.kexin.zookeeper.ha;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author KeXin
* @Date 2018/7/24 上午10:38
**/
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "zookeeper")
public class ZkClientConfig {
@Getter
@Setter
private String server;
@Getter
@Setter
private String znode;
@Getter
@Setter
private String client_id;
// 是否是leader 默认为false
public static boolean isLeader = false;
@Bean
public ZkClient getZkClient() throws Exception {
RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
CuratorFramework client = CuratorFrameworkFactory
.builder()
.connectString(server)
.connectionTimeoutMs(50000)
.sessionTimeoutMs(60000)
.retryPolicy(retryPolicy)
.namespace("testZK") //创建名称空间,指定后本client所创建的所有节点都在此目录下
.build();
LeaderLatch leaderLatch = new LeaderLatch(client,znode,client_id,LeaderLatch.CloseMode.NOTIFY_LEADER);
leaderLatch.addListener(new LeaderLatchListener() {
@Override
public void isLeader() {
log.info("this client is the leader");
isLeader = true;
}
@Override
public void notLeader() {
log.info("this client is not the leader");
isLeader = false;
}
});
ZkClient zkClient = new ZkClient(client,leaderLatch);
zkClient.startZKClient();
return zkClient;
}
}
package com.kexin.zookeeper.ha;
import lombok.Getter;
import lombok.Setter;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
/**
* @Author KeXin
* @Date 2018/7/24 上午10:34
**/
public class ZkClient {
@Getter
@Setter
private CuratorFramework client;
@Getter
@Setter
private LeaderLatch leaderLatch;
public ZkClient(CuratorFramework client, LeaderLatch leaderLatch){
this.client = client;
this.leaderLatch = leaderLatch;
}
/**
* 启动客户端
*
* @throws Exception
*/
public void startZKClient() throws Exception {
client.start();
leaderLatch.start();
}
/**
* 关闭客户端
*
* @throws Exception
*/
public void closeZKClient() throws Exception {
leaderLatch.close();
client.close();
}
/**
* 判断是否变为领导者
*
* @return
*/
public boolean hasLeadership() {
return leaderLatch.hasLeadership() && ZkClientConfig.isLeader;
}
}