java读取zk节点内容
pom.xml
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>2.8.0</version>
</dependency>
其中 curator使用的是guava16.0.1 如果使用高版本的guava可能会报错
curator-recipes依赖
-----curator-framework:2.8.0
-----guava:16.0.1
-----zookeeper:3.4.6
curator-framework:2.8.0
-----curator-client
-----guava:16.0.1
-----zookeeper:3.4.6
curator-client
-----guava:16.0.1
-----zookeeper:3.4.6
java读取zookeeper节点
包目录
src/main/java
zk.config
MiddlewareConstants
ZkConfigProperties
zk.curator
ZKClient
ZKCuratorHandler
zk.exception
ZKCommonException
ZKErrorCode
src/main/resources
zkconfig.properties
读取zk的主方法
import com.qbsea.zk.config.MiddlewareConstants;
import com.qbsea.zk.curator.ZKCuratorHandler;
import com.qbsea.zk.exception.ZKCommonException;
public class ZkClientMainTest {
public static void main(String[] args) throws ZKCommonException {
String zkPath = "/zookeeper/dfdb/tenetid";//zk的节点地址
try {
String zkDataStr = ZKCuratorHandler.queryExistNodeData(zkPath, MiddlewareConstants.DFDB_MIDDLEWARE_ID);
System.out.println("original="+zkDataStr);
} catch (ZKCommonException e) {
throw e;
}
}
}
curator包下的类
ZKCuratorHandler->queryExistNodeData
import com.qbsea.zk.config.ZkConfigProperties;
import com.qbsea.zk.exception.ZKCommonException;
import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import static com.qbsea.zk.exception.ZKErrorCode.ZK_IP_LIST_ILLEGAL_ERROR;
import static com.qbsea.zk.exception.ZKErrorCode.ZK_NOT_INITIALIZED_ERROR;
public class ZKCuratorHandler {
private static Logger logger = LoggerFactory.getLogger(ZKCuratorHandler.class);
private static final Map<String, ZKClient> zkClientsHolder = new ConcurrentHashMap<>();
public static ZKClient getZKClient(String middlewaredId) throws ZKCommonException {
initForMiddleware(middlewaredId);
if (!zkClientsHolder.containsKey(middlewaredId)) {
logger.error("ERROR: ZKClient has not been initialized for " + middlewaredId + " .Call initForMiddleware first.");
throw new ZKCommonException(ZK_NOT_INITIALIZED_ERROR, "ERROR: ZKClient has not been initialized for " + middlewaredId + ". Call initForMiddleware first.");
}
return zkClientsHolder.get(middlewaredId);
}
private static void initForMiddleware(String middlewaredId) throws ZKCommonException {
if (zkClientsHolder.containsKey(middlewaredId)) {
return;
}
synchronized (ZKCuratorHandler.class) {
if (zkClientsHolder.containsKey(middlewaredId)) {
return;
}
ZKClient zkClient;
String ipList = ZkConfigProperties.getKey("zk_ip");
if (StringUtils.isBlank(ipList)) {
throw new NullPointerException("您在访问zk时,传入的zk的ip地址为空");
}
zkClient = loadZkClient(middlewaredId,ipList);
zkClientsHolder.put(middlewaredId, zkClient);
}
}
private static ZKClient loadZkClient(String middlewaredId, String ipList) throws ZKCommonException {
logger.info("Trying to connect to " + middlewaredId + "zk.IpList=" + ipList);
if (ipList == null || "".equals(ipList.trim())) {
throw new ZKCommonException(ZK_IP_LIST_ILLEGAL_ERROR, "Failed to get ipList for zookeeper for " + middlewaredId);
}
for (ZKClient zkClient : zkClientsHolder.values()) {
if (zkClient.getIpList().equals(ipList)) {
logger.info("Found same ipList ,using current zkClient for " + middlewaredId + " ipList=" + ipList);
return zkClient;
}
}
//从配制文件中获取
int baseSleepTimeMs = StringUtils.isBlank(ZkConfigProperties.getKey("baseSleepTimeMs")) ? 2000 : Integer.parseInt(ZkConfigProperties.getKey("baseSleepTimeMs"));
int maxRetries = StringUtils.isBlank(ZkConfigProperties.getKey("maxRetries")) ? 3 : Integer.parseInt(ZkConfigProperties.getKey("maxRetries"));
int maxSleepMs = StringUtils.isBlank(ZkConfigProperties.getKey("maxSleepMs")) ? 10000 : Integer.parseInt(ZkConfigProperties.getKey("maxSleepMs"));
int sessionTimeoutMs = StringUtils.isBlank(ZkConfigProperties.getKey("sessionTimeoutMs")) ? 60000 : Integer.parseInt(ZkConfigProperties.getKey("sessionTimeoutMs"));
int connectionTimeoutMs = StringUtils.isBlank(ZkConfigProperties.getKey("connectionTimeoutMs")) ? 5000 : Integer.parseInt(ZkConfigProperties.getKey("connectionTimeoutMs"));
ZKClient zkClient = new ZKClient(middlewaredId, ipList, baseSleepTimeMs, maxRetries, maxSleepMs, sessionTimeoutMs, connectionTimeoutMs);
zkClient.start();
logger.info("Connected to " + middlewaredId + " zk. IpList = " + ipList);
return zkClient;
}
public static String queryExistNodeData(String path, String middlewareId) throws ZKCommonException {
CuratorFramework curatorFramework = getZKClient(middlewareId).getCuratorFramework();
//将返回值""修改为null,与方法的注释保持一致
String attrJson = null;
try {
Stat stat = curatorFramework.checkExists().forPath(path);
if (stat != null) {
byte[] byteNode = curatorFramework.getData().forPath(path);
attrJson = new String(byteNode, "utf-8");
}
} catch (Exception e) {
throw new ZKCommonException("FFFF", "获取当前路径的节点值失败,该节点为:" + path, e);
}
return attrJson;
}
}
ZKClient
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.BoundedExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ZKClient {
private static Logger logger = LoggerFactory.getLogger(ZKClient.class);
private String middlewareId;
private String ipList;
private int baseSleepTimeMs;
private int maxRetries;
private int maxSleepTimeMs;
private int sessionTimeoutMs;
private int connectionTimeoutMs;
private CuratorFramework curatorFramework;
public ZKClient(String middlewareId,String ipList,int baseSleepTimeMs,int maxRetries,int maxSleepTimeMs,int sessionTimeoutMs,int connectionTimeoutMs) {
this.middlewareId = middlewareId;
this.ipList = ipList;
this.baseSleepTimeMs = baseSleepTimeMs;
this.maxRetries = maxRetries;
this.maxSleepTimeMs = maxSleepTimeMs;
this.sessionTimeoutMs = sessionTimeoutMs;
this.connectionTimeoutMs = connectionTimeoutMs;
//maxSleepTimeMs * maxRetries must be less or equal than sessionTimeoutMs.
if (maxSleepTimeMs * maxRetries > sessionTimeoutMs) {
this.maxSleepTimeMs = sessionTimeoutMs / maxRetries;
}
//connectionTimeoutMs * maxRetries must be less or equal than sessioTimeoutMs.
if (connectionTimeoutMs * maxRetries > sessionTimeoutMs) {
this.connectionTimeoutMs = sessionTimeoutMs / maxRetries;
}
}
public void start() {
RetryPolicy retryPolicy = new BoundedExponentialBackoffRetry(baseSleepTimeMs, maxSleepTimeMs, maxRetries);
if (sessionTimeoutMs == 0 || connectionTimeoutMs == 0) {
curatorFramework = CuratorFrameworkFactory.newClient(ipList, retryPolicy);
} else {
curatorFramework = CuratorFrameworkFactory.newClient(ipList, sessionTimeoutMs, connectionTimeoutMs, retryPolicy);
}
//start the curator
curatorFramework.start();
}
//set and get metho
public String getMiddlewareId() {
return middlewareId;
}
public void setMiddlewareId(String middlewareId) {
this.middlewareId = middlewareId;
}
public String getIpList() {
return ipList;
}
public void setIpList(String ipList) {
this.ipList = ipList;
}
public int getBaseSleepTimeMs() {
return baseSleepTimeMs;
}
public void setBaseSleepTimeMs(int baseSleepTimeMs) {
this.baseSleepTimeMs = baseSleepTimeMs;
}
public int getMaxRetries() {
return maxRetries;
}
public void setMaxRetries(int maxRetries) {
this.maxRetries = maxRetries;
}
public int getMaxSleepTimeMs() {
return maxSleepTimeMs;
}
public void setMaxSleepTimeMs(int maxSleepTimeMs) {
this.maxSleepTimeMs = maxSleepTimeMs;
}
public int getSessionTimeoutMs() {
return sessionTimeoutMs;
}
public void setSessionTimeoutMs(int sessionTimeoutMs) {
this.sessionTimeoutMs = sessionTimeoutMs;
}
public int getConnectionTimeoutMs() {
return connectionTimeoutMs;
}
public void setConnectionTimeoutMs(int connectionTimeoutMs) {
this.connectionTimeoutMs = connectionTimeoutMs;
}
public CuratorFramework getCuratorFramework() {
return curatorFramework;
}
public void setCuratorFramework(CuratorFramework curatorFramework) {
this.curatorFramework = curatorFramework;
}
}
config包下的两个类
MiddlewareConstants
public class MiddlewareConstants {
public static final String DFDB_MIDDLEWARE_ID = "dfdb";
}
ZkConfigProperties
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
public class ZkConfigProperties {
private static Map<String, String> dataMap = new ConcurrentHashMap<>();
public static void main(String[] args) {
String value = getKey("zk_ip");
System.out.println("value="+value);
}
public static String getKey(String key) {
String value = dataMap.get(key);
if (StringUtils.isNotBlank(value)) {
return value;
}
Properties properties = new Properties();
InputStream in = ZkConfigProperties.class.getClassLoader().getResourceAsStream("zkconfig.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
return null;
}
String propertyValue = properties.getProperty(key);
if (StringUtils.isNotBlank(propertyValue)) {
dataMap.put(key, propertyValue);
}
return propertyValue;
}
}
exception
ZKCommonException
public class ZKCommonException extends Exception {
private String code;
private String desc;
public ZKCommonException(String code, String desc) {
super(desc);
this.code = code;
this.desc = code;
}
public ZKCommonException(String code, String desc, Throwable cause) {
super(desc, cause);
this.code = code;
this.desc = desc;
}
public ZKCommonException( String desc, Throwable cause) {
super(desc, cause);
this.desc = desc;
}
@Override
public String getLocalizedMessage() {
return this.desc;
}
//set and get method
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
ZKErrorCode
public class ZKErrorCode {
public static final String ZK_CONFIG_ERROR = "ffff";
public static final String ZK_IP_LIST_ILLEGAL_ERROR = "ffff";
public static final String ZK_NOT_INITIALIZED_ERROR = "ffff";
}
resources下的zkconfig.properties
zk_ip=127.0.0.1:2181
#等待重试的间隔时间初始值(单位:ms)
baseSleepTimeMs=1000
#最大重试次数#dfdb_config.properties里取
maxRetries=1
#默认每次重试操作zk或获取zk数据时的最大超时时间(单位:ms)
maxSleepMs=10000
#zk会话超时时间,连接超时时间(单位:ms)#
sessionTimeoutMs=3000
#连接超时时间#
connectionTimeoutMs=3000
ZooInspector往zk节点写内容乱码
有时使用ZooInspector工具时,往zk上写内容时会出现乱码,这时通过启动参数指定一下就可以
java -Dfile.encoding=utf-8 -Xms512m -Xmx1024m -jar zookeeper-dev-ZooInspector.jar