Posted In: Micro, Service

Micro services – configuration management using ETCD

This post shows one of the ways to create micro services architecture with enterprise level configuration services

etcd is a distributed key value store that provides a reliable way to store data across a cluster of machines. It’s open-source and available on GitHub. etcd gracefully handles leader elections during network partitions and will tolerate machine failure, including the leader.
Install ETCD from https://github.com/coreos/etcd/releases/

Steps

1. Start etcd service. (Click on etcd.exe on windows)
2. Add jetcd java client library to maven
3. Add and fetch configuration parameters

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
</dependency>
<dependency>
	<groupId>com.coreos</groupId>
	<artifactId>jetcd-core</artifactId>
	<version>0.0.1</version>
</dependency>
package com.javausecase.etcd;

import java.util.concurrent.CompletableFuture;

import com.coreos.jetcd.Client;
import com.coreos.jetcd.KV;
import com.coreos.jetcd.data.ByteSequence;
import com.coreos.jetcd.data.KeyValue;
import com.coreos.jetcd.kv.DeleteResponse;
import com.coreos.jetcd.kv.GetResponse;

public class App {
	public static void main(String[] args) throws Exception {
		System.out.println("Start");
		// create client
		Client client = Client.builder().endpoints("http://localhost:2379").build();
		KV kvClient = client.getKVClient();

		ByteSequence key = ByteSequence.fromString("test_key");
		ByteSequence value = ByteSequence.fromString("test_value");

		// put the key-value
		kvClient.put(key, value).get();
		// get the CompletableFuture
		CompletableFuture<GetResponse> getFuture = kvClient.get(key);
		// get the value from CompletableFuture
		GetResponse response = getFuture.get();
		for(KeyValue keyValue : response.getKvs()) {
			System.out.println("key=" + keyValue.getKey().toStringUtf8() 
					+ "::value=" + keyValue.getValue().toStringUtf8());
		}
		// delete the key
		DeleteResponse deleteRangeResponse = kvClient.delete(key).get();
		getFuture = kvClient.get(key);
		response = getFuture.get();
		for(KeyValue keyValue : response.getKvs()) {
			System.out.println("key=" + keyValue.getKey().toStringUtf8() 
					+ "::value=" + keyValue.getValue().toStringUtf8());
		}
		client.close();
		System.out.println("End");
	}
}

Tags:

by , on February 13th, 2018

  • Categories