org.yx.conf.AbstractZKConfig Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of sumk Show documentation
Show all versions of sumk Show documentation
A quick developing framewort for internet company
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.yx.conf;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.yx.log.ConsoleLog;
import org.yx.log.RawLog;
import org.yx.util.ZkClientHelper;
public abstract class AbstractZKConfig extends AbstractRefreshableSystemConfig {
protected NamePairs zkInfo = new NamePairs((String) null);
private Charset charset = StandardCharsets.UTF_8;
private IZkDataListener listener = new IZkDataListener() {
@Override
public void handleDataChange(String dataPath, Object data) throws Exception {
try {
ConsoleLog.get("sumk.zk.data").debug("data in zk path {} changed", dataPath);
AbstractZKConfig.this.setZkInfo(new NamePairs(new String((byte[]) data, charset)));
onRefresh();
} catch (Exception e) {
RawLog.error("sumk.conf", e);
}
}
@Override
public void handleDataDeleted(String dataPath) throws Exception {
AbstractZKConfig.this.setZkInfo(new NamePairs((String) null));
onRefresh();
}
};
protected void setZkInfo(NamePairs info) {
zkInfo = info == null ? new NamePairs((String) null) : info;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
protected void init() {
String zkUrl = getZkUrl();
NamePairs info = ZKConfigHandler.readAndListen(zkUrl, getDataPath(), listener);
this.setZkInfo(info);
}
public void stop() {
try {
String zkUrl = getZkUrl();
ZkClient client = ZkClientHelper.getZkClient(zkUrl);
client.unsubscribeDataChanges(getDataPath(), listener);
this.started = false;
} catch (Exception e) {
RawLog.error("sumk.conf", e.getMessage(), e);
}
}
protected abstract String getDataPath();
protected abstract String getZkUrl();
@Override
public String get(String key) {
return zkInfo.getValue(key);
}
@Override
public Set keys() {
return zkInfo.keys();
}
@Override
public Map values() {
return zkInfo.values();
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy