Java中etcd的使用
# demo
# 这里的代码和golang客户端基本是对齐的,java使用观察者模式进行数据的监听
KV kvClient = etcdClient.getKVClient();
Lease leaseClient = etcdClient.getLeaseClient();
// Generate a random value for the key
String value = GetIP.getAddress() + ":" + port;
log.info("pod ip: " + value);
// Create a new lease
long leaseId = leaseClient.grant(LEASE_TTL).get().getID();
// signhub.algorithm.{site_name}.{action}/{lease_id}
String[] joinKey = {"signhub", "algorithm", getGroup().toString().toLowerCase(), getAction().toString().toLowerCase()};
String registerKey = String.join(".", joinKey);
System.out.println(registerKey);
ByteSequence key = ByteSequence.from(registerKey + "/" + leaseId, StandardCharsets.UTF_8);
ByteSequence val = ByteSequence.from(value, StandardCharsets.UTF_8);
kvClient.put(key, val).get();
AtomicReference<io.etcd.jetcd.lease.LeaseKeepAliveResponse> resp = new AtomicReference<>();
AtomicReference<Throwable> error = new AtomicReference<>();
StreamObserver<io.etcd.jetcd.lease.LeaseKeepAliveResponse> observer = Observers.<LeaseKeepAliveResponse>builder()
.onNext(resp::set)
.onError(error::set)
.build();
long leaseID = leaseClient.grant(5, 10, TimeUnit.SECONDS).get().getID();
kvClient.put(key, val, PutOption.newBuilder().withLeaseId(leaseID).build()).get();
leaseClient.keepAlive(leaseID, observer);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# etcd官方demo
https://github.com/etcd-io/jetcd/blob/main/jetcd-core/src/test/java/io/etcd/jetcd/impl/LeaseTest.java
# 文档
https://github.com/kekingcn/kkbinlog/blob/master/%E6%B5%85%E6%9E%90jetcd%E4%B8%AD%E7%9A%84KeepAlive%E5%AE%9E%E7%8E%B0.md
1
2
3
4
5
2
3
4
5
上次更新: 2023-08-11 10:18:21