How to use etcd v2 and v3 api to get configuration and monitor configuration changes in java

etcd is very similar to zookeeper and can be used for configuration management. And etcd can be used in the currently popular Kubernetes.

But etcd provides two APIs for the v2 version and the v3 version. Let's now introduce the use of these two versions of the api separately.

1. Etcd V2 API

1. In the java project, use maven to introduce the java api operation jar package of etcd v2

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.21.Final</version>
</dependency>
<dependency>
<groupId>org.mousio</groupId>
<artifactId>etcd4j</artifactId>
<version>2.15.0</version>
</dependency>

2、etcd的链接
import mousio.etcd4j.EtcdClient; 
import java.io.InputStream;
import java.net.URI;
import java.util.Properties;


public class EtcdUtil {
//etcd client link
private static EtcdClient client = null;
// link initialization
public static synchronized EtcdClient getClient(){
if (null == client){
client = new EtcdClient (URI.create(properties.getProperty("http://127.0.0.1:2379")));
}
return client;
}
}
3 , How to get the etcd configuration and monitor the configuration
//Initialize get the etcd configuration and monitor the configuration
private void initEtcdConfig() { 
EtcdKeysResponse dataTree ;
try {
final EtcdClient etcdClient = EtcdUtil.getClient();
//Get the configuration under the etcd folder named etcd
EtcdKeyGetRequest etcdKeyGetRequest = etcdClient.getDir("ETCD").consistent();
dataTree = etcdKeyGetRequest.send().get();
//Get etcd version
System.out.println("ETCD's version:"+etcdClient.getVersion());
getConfig("/etcd/example.config",dataTree) ; //Load configuration items
   //Start a thread to listen
startListenerThread(etcdClient);
} catch (Exception e) {
System.out.println("EtcdClient init cause Exception:"+e.getMessage());
e.printStackTrace( );
}
}
private String getConfig(String configFile,EtcdKeysResponse dataTree){
if(null != dataTree && dataTree.getNode().getNodes().size()>0){
for(EtcdKeysResponse.EtcdNode node:dataTree.getNode().getNodes()){
if(node.getKey().equals(configFile)){
return node.getValue();
}
}
}
System.out.println("Etcd configFile"+ configFile+"is not exist,Please Check");
return null;
}
public void startListenerThread(EtcdClient etcdClient){
new Thread(()->{
startListener(etcdClient);
}).start();
}
public void startListener(EtcdClient etcdClient){
ResponsePromise promise =null;
try {
promise = etcdClient.getDir(SYSTEM_NAME).recursive().waitForChange().consistent().send();
promise.addListener(promisea -> {
logger.info("found ETCD's config:{}cause change",ETCD_CONFIG_FILE_NAME);
try {
getConfig("/ETCD/example.config", etcdClient.getDir("ETCD").consistent().send().get()); //加载配置项
} catch (Exception e) {
e.printStackTrace();
logger.info("listen etcd 's config change cause exception:{}",e.getMessage());
}
startListener(etcdClient);
});
} catch (Exception e) {
startListener(etcdClient);
System.out.println("listen etcd 's config change cause exception:"+e.getMessage());
e.printStackTrace();

}
}
4、使用dcmp管理 etcd的配置项
dcmp is an etcd configuration interface developed in go language. When insufficient, this only supports v2 API. The address of the project:

https://github.com/silenceper/dcmp

 

1. Etcd V3 API

1. Introduce the following dependencies into the project

<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.15.Final</version>
</dependency>
<dependency>
<groupId>com.coreos</groupId>
<artifactId>jetcd-core</artifactId>
<version>0.0.2</version>
</dependency>
2、v3 api操作工具类
public class EtcdUtil { 
//etcl client link
private static Client client = null;
//Link initialization
public static synchronized Client getEtclClient(){
if(null == client){
client = Client.builder().endpoints(props.getProperty ("http://127.0.0.1:2379")).build();
}
return client;
}

/**
* Get the corresponding value according to the specified configuration name
* @param key configuration item
* @return
* @throws Exception
*/
public static String getEtcdValueByKey(String key) throws Exception {
List<KeyValue> kvs = EtcdUtil.getEtclClient().getKVClient().get(ByteSequence.fromString(key)).get().getKvs();
if(kvs.size()>0){
String value = kvs.get(0).getValue().toStringUtf8();
return value;
}
else {
return null;
}
}

/**
* 新增或者修改指定的配置
* @param key
* @param value
* @return
*/
public static void putEtcdValueByKey(String key,String value) throws Exception{
EtcdUtil.getEtclClient().getKVClient().put(ByteSequence.fromString(key),ByteSequence.fromBytes(value.getBytes("utf-8")));

}

/**
* 删除指定的配置
* @param key
* @return
*/
public static void deleteEtcdValueByKey(String key){
EtcdUtil.getEtclClient().getKVClient().delete(ByteSequence.fromString(key));

}
}
//V3 api configuration initialization and monitoring
public void init(){
try { 
//Load configuration
getConfig(EtcdUtil.getEtclClient().getKVClient().get(ByteSequence.fromString(ETCD_CONFIG_FILE_NAME)).get().getKvs());
//Start listening thread
new Thread(() -> {
//Monitor a configuration
Watch.Watcher watcher = EtcdUtil.getEtclClient().getWatchClient().watch(ByteSequence.fromString("etcd_key"));
try {
while(true) {
watcher.listen().getEvents( ).stream().forEach(watchEvent -> {
KeyValue kv = watchEvent.getKeyValue();
            //Get the event change type
            System.out.println(watchEvent.getEventType());
   //Get the changed key
System.out .println(kv.getKey().toStringUtf8());
          //Get the changed value 
String afterChangeValue = kv.getValue().toStringUtf8();

});
}
} catch (InterruptedException e) {
e.printStackTrace();

}
}).start();
} catch (Exception e ) {
e.printStackTrace();

}

}
private String getConfig(List<KeyValue> kvs){
if(kvs.size()>0){
String config = kvs.get(0).getValue().toStringUtf8();
logger.info("etcd 's config:{} 's configValue is :{}",ETCD_CONFIG_FILE_NAME,config);
return config;
}
else {
return null;
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325074886&siteId=291194637