liubao68 commented on code in PR #4564:
URL: 
https://github.com/apache/servicecomb-java-chassis/pull/4564#discussion_r1817518373


##########
service-registry/registry-etcd/src/main/java/org/apache/servicecomb/registry/etcd/EtcdDiscovery.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.servicecomb.registry.etcd;
+
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CompletableFuture;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.servicecomb.config.BootStrapProperties;
+import org.apache.servicecomb.foundation.common.utils.JsonUtils;
+import org.apache.servicecomb.registry.api.Discovery;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.env.Environment;
+
+import com.google.common.collect.Lists;
+
+import io.etcd.jetcd.ByteSequence;
+import io.etcd.jetcd.Client;
+import io.etcd.jetcd.KeyValue;
+import io.etcd.jetcd.Watch;
+import io.etcd.jetcd.kv.GetResponse;
+import io.etcd.jetcd.options.GetOption;
+import io.etcd.jetcd.options.WatchOption;
+
+public class EtcdDiscovery implements Discovery<EtcdDiscoveryInstance> {
+
+  private Environment environment;
+
+  private String basePath;
+
+  private EtcdRegistryProperties etcdRegistryProperties;
+
+  private Client client;
+
+  private InstanceChangedListener<EtcdDiscoveryInstance> 
instanceChangedListener;
+
+  private static final Logger LOGGER = 
LoggerFactory.getLogger(EtcdDiscovery.class);
+
+  @Autowired
+  @SuppressWarnings("unused")
+  public void setEnvironment(Environment environment) {
+    this.environment = environment;
+  }
+
+  @Autowired
+  @SuppressWarnings("unused")
+  public void setEtcdRegistryProperties(EtcdRegistryProperties 
etcdRegistryProperties) {
+    this.etcdRegistryProperties = etcdRegistryProperties;
+  }
+
+  @Override
+  public String name() {
+    return EtcdConst.ETCD_REGISTRY_NAME;
+  }
+
+  @Override
+  public boolean enabled(String application, String serviceName) {
+    return 
environment.getProperty(String.format(EtcdConst.ETCD_DISCOVERY_ENABLED, 
application, serviceName),
+        boolean.class, true);
+  }
+
+  @Override
+  public List<EtcdDiscoveryInstance> findServiceInstances(String application, 
String serviceName) {
+
+    String prefixPath = basePath + "/" + application + "/" + serviceName;
+    SingletonManager.getInstance().computeIfAbsent(prefixPath, serName -> {
+      Watch watchClient = client.getWatchClient();
+      try {
+        ByteSequence prefixByteSeq = ByteSequence.from(prefixPath, 
Charset.defaultCharset());
+        watchClient.watch(
+            prefixByteSeq,
+            WatchOption.builder().withPrefix(prefixByteSeq).build(),
+            resp -> {
+              Map<String, EtcdDiscoveryInstance> instanceMap = 
SingletonManager.getInstance()
+                  .get("instance:" + prefixPath);
+              resp.getEvents().forEach(event -> {
+                String key = 
event.getKeyValue().getKey().toString(Charset.defaultCharset());
+                switch (event.getEventType()) {
+                  case PUT -> {
+                    EtcdDiscoveryInstance newInstance = 
getEtcdDiscoveryInstance(event.getKeyValue());
+                    instanceMap.put(key, newInstance);
+                  }
+                  case DELETE -> instanceMap.remove(key);
+                  default -> LOGGER.error("unkonw event");
+                }
+              });
+              List<EtcdDiscoveryInstance> discoveryInstanceList = new 
ArrayList<>(instanceMap.values());
+              instanceChangedListener.onInstanceChanged(name(), application, 
serviceName, discoveryInstanceList);
+            }
+        );
+      } catch (Exception e) {
+        LOGGER.error("Failed to add watch", e);
+      }
+      return watchClient;
+    });
+
+    List<KeyValue> endpointKv = getValuesByPrefix(prefixPath);
+    List<EtcdDiscoveryInstance> etcdDiscoveryInstances = 
convertServiceInstanceList(endpointKv);
+    SingletonManager.getInstance().computeIfAbsent("instance:" + prefixPath, v 
-> etcdDiscoveryInstances.stream()
+        .collect(
+            Collectors.toConcurrentMap(instance -> prefixPath + "/" + 
instance.getInstanceId(), Function.identity())));
+    return etcdDiscoveryInstances;
+  }
+
+  public List<KeyValue> getValuesByPrefix(String prefix) {
+
+    CompletableFuture<GetResponse> getFuture = client.getKVClient()
+        .get(ByteSequence.from(prefix, StandardCharsets.UTF_8),
+            GetOption.builder().withPrefix(ByteSequence.from(prefix, 
StandardCharsets.UTF_8)).build());
+    GetResponse response = MuteExceptionUtil.builder().withLog("get kv by 
prefix error")
+        .executeCompletableFuture(getFuture);
+    return response.getKvs();
+  }
+
+  private List<EtcdDiscoveryInstance> 
convertServiceInstanceList(List<KeyValue> keyValueList) {
+
+    List<EtcdDiscoveryInstance> list = 
Lists.newArrayListWithExpectedSize(keyValueList.size());
+    for (KeyValue keyValue : keyValueList) {
+      EtcdDiscoveryInstance etcdDiscoveryInstance = 
getEtcdDiscoveryInstance(keyValue);
+      list.add(etcdDiscoveryInstance);
+    }
+    return list;
+  }
+
+  private static EtcdDiscoveryInstance getEtcdDiscoveryInstance(KeyValue 
keyValue) {
+    String valueJson = new String(keyValue.getValue().getBytes(), 
Charset.defaultCharset());
+
+    EtcdInstance etcdInstance = MuteExceptionUtil.builder()
+        .withLog("convert json value to obj from etcd failure, {}", valueJson)
+        .executeFunctionWithDoubleParam(JsonUtils::readValue, 
valueJson.getBytes(StandardCharsets.UTF_8),
+            EtcdInstance.class);
+    EtcdDiscoveryInstance etcdDiscoveryInstance = new 
EtcdDiscoveryInstance(etcdInstance);
+    return etcdDiscoveryInstance;
+  }
+
+  @Override
+  public List<String> findServices(String application) {
+
+    String prefixPath = basePath + "/" + application;
+    List<KeyValue> endpointKv = getValuesByPrefix(prefixPath);
+    return endpointKv.stream().map(kv -> 
kv.getKey().toString(StandardCharsets.UTF_8)) // 转换 ByteSequence 为 String

Review Comment:
   Use English if possible. 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to