import com.ctrip.framework.apollo.ConfigService;
import com.dianping.cat.Cat;
import com.weimob.artemis.http.constant.Constants;
import com.weimob.artemis.http.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 要写注释呀
*/
@Slf4j
@Component
public class ZkPointHandler {
@Value("${zookeeper.url}")
public String zookeeperUrl;
@Value("${dubbo.protocol.port}")
private String protocolPort;
@PostConstruct
public void create() {
Cat.logEvent("ZKCurator init zk address", zookeeperUrl);
ZkClient zkc = new ZkClient(new ZkConnection(zookeeperUrl), 5000);
zkc.setZkSerializer(new MyZkSerializer());
//获取本地的ip地址
String localIp = IpUtils.getLocalIps();
if (!zkc.exists(Constants.ARTEMIS_ZK_HTTP_SERVICE)) {
zkc.createPersistent(Constants.ARTEMIS_ZK_HTTP_SERVICE);
}
//创建临时节点
String path = Constants.ARTEMIS_ZK_HTTP_SERVICE + "/" + localIp + ":" + protocolPort;
if (!zkc.exists(path)) {
zkc.createEphemeral(path);
}
//防止节点丢失,重新创建
ScheduledExecutorService checkZkPoint = Executors.newSingleThreadScheduledExecutor();
checkZkPoint.scheduleWithFixedDelay(this::checkPoint, 1, 1, TimeUnit.MINUTES);
}
public List<String> getAddressList() {
String zkAddress = ConfigService.getConfig("zookeeper").getProperty("zookeeper.url", "");
log.info("zkAddress {}", zkAddress);
ZkClient zkc = new ZkClient(new ZkConnection(zkAddress), 5000);
//防止zk没有父节点
if (!zkc.exists(Constants.ARTEMIS_ZK_HTTP_SERVICE)) {
zkc.createPersistent(Constants.ARTEMIS_ZK_HTTP_SERVICE);
}
//从zk获取当前节点数
List<String> list = zkc.getChildren(Constants.ARTEMIS_ZK_HTTP_SERVICE);
Cat.logEvent(" artmis zk info from list", list.toString());
return list;
}
private void checkPoint() {
ZkClient zkc = new ZkClient(new ZkConnection(zookeeperUrl), 5000);
zkc.setZkSerializer(new MyZkSerializer());
//获取本地的ip地址
String localIp = IpUtils.getLocalIps();
if (!zkc.exists(Constants.ARTEMIS_ZK_HTTP_SERVICE)) {
zkc.createPersistent(Constants.ARTEMIS_ZK_HTTP_SERVICE);
}
//创建临时节点
String path = Constants.ARTEMIS_ZK_HTTP_SERVICE + "/" + localIp + ":" + protocolPort;
if (!zkc.exists(path)) {
zkc.createEphemeral(path);
}
}
}
zookeeper zk 创建节点
最新推荐文章于 2024-10-31 15:04:51 发布