You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by GitBox <gi...@apache.org> on 2022/09/21 01:28:49 UTC

[GitHub] [shardingsphere] terrymanu commented on a diff in pull request #20984: Support Nacos to persist metadata in cluster mode

terrymanu commented on code in PR #20984:
URL: https://github.com/apache/shardingsphere/pull/20984#discussion_r975937570


##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/KeyValue.java:
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * Key value.
+ */
+@AllArgsConstructor
+@Data

Review Comment:
   Is it necessary to use @Data here? 



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/KeyValue.java:
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * Key value.
+ */
+@AllArgsConstructor

Review Comment:
   Please use @RequiredArgsConstructor



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/NacosRepository.java:
##########
@@ -0,0 +1,371 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.naming.NamingFactory;
+import com.alibaba.nacos.api.naming.NamingService;
+import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import com.alibaba.nacos.common.utils.CollectionUtils;
+import com.alibaba.nacos.common.utils.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryConfiguration;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryException;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.entity.KeyValue;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.entity.RegisterMetadata;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.listener.NamingEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.props.NacosProperties;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.props.NacosPropertyKey;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Registry repository of Nacos.
+ */
+@Slf4j
+public final class NacosRepository implements ClusterPersistRepository {
+    
+    private NamingService client;
+    
+    private NacosProperties nacosProps;
+    
+    @Override
+    public void init(final ClusterPersistRepositoryConfiguration config) {
+        nacosProps = new NacosProperties(config.getProps());
+        initClient(config);
+        initRegisterMetadata();
+    }
+    
+    private void initClient(final ClusterPersistRepositoryConfiguration config) {
+        Properties props = new Properties();
+        props.setProperty("serverAddr", config.getServerLists());
+        props.setProperty("namespace", config.getNamespace());
+        try {
+            client = NamingFactory.createNamingService(props);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    private void initRegisterMetadata() {
+        try {
+            String ip = nacosProps.getValue(NacosPropertyKey.CLUSTER_IP);
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                AtomicInteger port = client.getAllInstances(registerMetadata.name(), false).stream()
+                        .filter(filterInstance -> StringUtils.equals(filterInstance.getIp(), ip)).max(Comparator.comparing(Instance::getPort))
+                        .map(convert -> new AtomicInteger(convert.getPort())).orElse(new AtomicInteger(Integer.MIN_VALUE));
+                registerMetadata.setPort(port);
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persistEphemeral(final String key, final String value) {
+        try {
+            if (Objects.isNull(value)) {
+                throw new IllegalArgumentException("Value cannot be null");
+            }
+            if (!findExisted(key, true).isEmpty()) {
+                delete(key);
+            }
+            put(key, value, true);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persistExclusiveEphemeral(final String key, final String value) {
+        try {
+            if (!findExisted(key, true).isEmpty()) {
+                throw new IllegalStateException("Key: " + key + " already exists");
+            }
+            put(key, value, true);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public boolean persistLock(final String lockKey, final long timeoutMillis) {
+        // TODO
+        return false;
+    }
+    
+    @Override
+    public void deleteLock(final String lockKey) {
+        // TODO
+    }
+    
+    @Override
+    public void watch(final String key, final DataChangedEventListener listener) {
+        try {
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                NamingEventListener eventListener = registerMetadata.getListener();
+                if (Objects.isNull(eventListener)) {
+                    Map<String, DataChangedEventListener> parentPathListenerMap = new HashMap<>();
+                    parentPathListenerMap.put(key, listener);
+                    eventListener = new NamingEventListener(parentPathListenerMap);
+                    registerMetadata.setListener(eventListener);
+                    client.subscribe(registerMetadata.name(), eventListener);
+                } else {
+                    eventListener.put(key, listener);
+                }
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public String get(final String key) {
+        try {
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                Optional<Instance> optional = findExisted(key, registerMetadata.isEphemeral()).stream().max(Comparator.comparing(MetadataUtil::getTimestamp));
+                if (optional.isPresent()) {
+                    return MetadataUtil.getValue(optional.get());
+                }
+            }
+            return null;
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public List<String> getChildrenKeys(final String key) {
+        try {
+            Stream<String> concatKeys = Stream.empty();
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                Stream<String> keys = findExisted(registerMetadata.isEphemeral()).stream()
+                        .map(instance -> {
+                            String fullPath = MetadataUtil.getKey(instance);
+                            if (fullPath.startsWith(key + PATH_SEPARATOR)) {
+                                String pathWithoutPrefix = fullPath.substring((key + PATH_SEPARATOR).length());
+                                return pathWithoutPrefix.contains(PATH_SEPARATOR) ? pathWithoutPrefix.substring(0, pathWithoutPrefix.indexOf(PATH_SEPARATOR)) : pathWithoutPrefix;
+                            }
+                            return null;
+                        }).filter(Objects::nonNull);
+                concatKeys = Stream.concat(concatKeys, keys);
+            }
+            return concatKeys.distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persist(final String key, final String value) {
+        try {
+            if (Objects.isNull(value)) {
+                throw new IllegalArgumentException("Value cannot be null");
+            }
+            Optional<Instance> optional = findExisted(key, false).stream().max(Comparator.comparing(MetadataUtil::getTimestamp));
+            if (optional.isPresent()) {
+                update(optional.get(), value);
+            } else {
+                put(key, value, false);
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    private void put(final String key, final String value, final boolean ephemeral) throws NacosException, InterruptedException {
+        final List<KeyValue> keyValues = buildParentPath(key);
+        RegisterMetadata registerMetadata = RegisterMetadata.of(ephemeral);
+        Instance instance = new Instance();
+        instance.setIp(nacosProps.getValue(NacosPropertyKey.CLUSTER_IP));
+        instance.setPort(registerMetadata.getPort());
+        instance.setEphemeral(ephemeral);
+        Map<String, String> metadataMap = new HashMap<>(5, 1);
+        if (ephemeral) {
+            fillEphemeralMetadata(metadataMap);
+        }
+        metadataMap.put(key, value);
+        metadataMap.put(MetadataUtil.UTC_ZONE_OFFSET.toString(), String.valueOf(MetadataUtil.getTimestamp()));
+        instance.setMetadata(metadataMap);
+        client.registerInstance(registerMetadata.name(), instance);
+        keyValues.add(new KeyValue(key, value, ephemeral));
+        waitValue(keyValues);
+    }
+    
+    private List<KeyValue> buildParentPath(final String key) throws NacosException {
+        List<KeyValue> keyValues = new LinkedList<>();
+        StringBuilder parentPath = new StringBuilder();
+        String[] partPath = key.split(PATH_SEPARATOR);
+        for (int index = 1; index < partPath.length - 1; index++) {
+            String path = parentPath.append(PATH_SEPARATOR).append(partPath[index]).toString();
+            if (findExisted(path, false).isEmpty()) {
+                keyValues.addAll(build(path));
+            }
+        }
+        return keyValues;

Review Comment:
   Please name as `result` for return value



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/WatchData.java:
##########
@@ -0,0 +1,39 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.Data;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+
+/**
+ * Watch data.
+ */
+@Data
+@RequiredArgsConstructor
+public class WatchData {

Review Comment:
   Please add final if class does not design for extension



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/RegisterMetadata.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lombok.Setter;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.listener.NamingEventListener;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+/**
+ * Register metadata.
+ */
+@RequiredArgsConstructor
+public enum RegisterMetadata {
+    
+    /**
+     * persistent.
+     */
+    PERSISTENT(false),
+    
+    /**
+     * ephemeral.
+     */
+    EPHEMERAL(true);
+    
+    @Setter
+    private AtomicInteger port;
+    
+    @Setter
+    @Getter
+    private NamingEventListener listener;
+    
+    @Getter
+    private final boolean ephemeral;
+    
+    /**
+     * Find corresponding registerMetadata.
+     *
+     * @param isEphemeral isEphemeral
+     * @return registerMetadata
+     */
+    public static RegisterMetadata of(final boolean isEphemeral) {
+        return Stream.of(values())
+                .filter(registerMetadata -> registerMetadata.ephemeral == isEphemeral).findAny()
+                .orElseThrow(() -> new IllegalArgumentException("Status not exist: " + isEphemeral));
+    }
+    
+    /**
+     * This is to ensure that port is different from the last time when persisting.
+     *
+     * @return fake port
+     */
+    public int getPort() {
+        int port = this.port.incrementAndGet();
+        if (port == Integer.MIN_VALUE) {
+            throw new IllegalStateException("Specified cluster ip exceeded the maximum number of persisting");
+        }
+        return port;

Review Comment:
   Please name as `result` for return value



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/KeyValue.java:
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+
+/**
+ * Key value.
+ */
+@AllArgsConstructor
+@Data
+public class KeyValue {

Review Comment:
   Please add final if class does not design for extension



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/NamingEventListener.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.listener.Event;
+import com.alibaba.nacos.api.naming.listener.EventListener;
+import com.alibaba.nacos.api.naming.listener.NamingEvent;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Naming event listener.
+ */
+@RequiredArgsConstructor
+public class NamingEventListener implements EventListener {
+    
+    private Map<String, Instance> preInstances = new HashMap<>();

Review Comment:
   What does `preInstances` mean?



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/utils/MetadataUtil.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.utils;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.SneakyThrows;
+
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+
+/**
+ * Metadata util.
+ */
+public class MetadataUtil {

Review Comment:
   Please add private constructor for util class



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/NamingEventListener.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.listener.Event;
+import com.alibaba.nacos.api.naming.listener.EventListener;
+import com.alibaba.nacos.api.naming.listener.NamingEvent;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Naming event listener.
+ */
+@RequiredArgsConstructor
+public class NamingEventListener implements EventListener {

Review Comment:
   Please add final if class does not design for extension



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/RegisterMetadata.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lombok.Setter;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.listener.NamingEventListener;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+/**
+ * Register metadata.
+ */
+@RequiredArgsConstructor
+public enum RegisterMetadata {
+    
+    /**
+     * persistent.
+     */
+    PERSISTENT(false),
+    
+    /**
+     * ephemeral.
+     */
+    EPHEMERAL(true);

Review Comment:
   How about just use boolean?



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/NacosRepository.java:
##########
@@ -0,0 +1,371 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.naming.NamingFactory;
+import com.alibaba.nacos.api.naming.NamingService;
+import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import com.alibaba.nacos.common.utils.CollectionUtils;
+import com.alibaba.nacos.common.utils.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryConfiguration;
+import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryException;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.entity.KeyValue;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.entity.RegisterMetadata;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.listener.NamingEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.props.NacosProperties;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.props.NacosPropertyKey;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Properties;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Registry repository of Nacos.
+ */
+@Slf4j
+public final class NacosRepository implements ClusterPersistRepository {
+    
+    private NamingService client;
+    
+    private NacosProperties nacosProps;
+    
+    @Override
+    public void init(final ClusterPersistRepositoryConfiguration config) {
+        nacosProps = new NacosProperties(config.getProps());
+        initClient(config);
+        initRegisterMetadata();
+    }
+    
+    private void initClient(final ClusterPersistRepositoryConfiguration config) {
+        Properties props = new Properties();
+        props.setProperty("serverAddr", config.getServerLists());
+        props.setProperty("namespace", config.getNamespace());
+        try {
+            client = NamingFactory.createNamingService(props);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    private void initRegisterMetadata() {
+        try {
+            String ip = nacosProps.getValue(NacosPropertyKey.CLUSTER_IP);
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                AtomicInteger port = client.getAllInstances(registerMetadata.name(), false).stream()
+                        .filter(filterInstance -> StringUtils.equals(filterInstance.getIp(), ip)).max(Comparator.comparing(Instance::getPort))
+                        .map(convert -> new AtomicInteger(convert.getPort())).orElse(new AtomicInteger(Integer.MIN_VALUE));
+                registerMetadata.setPort(port);
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persistEphemeral(final String key, final String value) {
+        try {
+            if (Objects.isNull(value)) {
+                throw new IllegalArgumentException("Value cannot be null");
+            }
+            if (!findExisted(key, true).isEmpty()) {
+                delete(key);
+            }
+            put(key, value, true);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persistExclusiveEphemeral(final String key, final String value) {
+        try {
+            if (!findExisted(key, true).isEmpty()) {
+                throw new IllegalStateException("Key: " + key + " already exists");
+            }
+            put(key, value, true);
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public boolean persistLock(final String lockKey, final long timeoutMillis) {
+        // TODO
+        return false;
+    }
+    
+    @Override
+    public void deleteLock(final String lockKey) {
+        // TODO
+    }
+    
+    @Override
+    public void watch(final String key, final DataChangedEventListener listener) {
+        try {
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                NamingEventListener eventListener = registerMetadata.getListener();
+                if (Objects.isNull(eventListener)) {
+                    Map<String, DataChangedEventListener> parentPathListenerMap = new HashMap<>();
+                    parentPathListenerMap.put(key, listener);
+                    eventListener = new NamingEventListener(parentPathListenerMap);
+                    registerMetadata.setListener(eventListener);
+                    client.subscribe(registerMetadata.name(), eventListener);
+                } else {
+                    eventListener.put(key, listener);
+                }
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public String get(final String key) {
+        try {
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                Optional<Instance> optional = findExisted(key, registerMetadata.isEphemeral()).stream().max(Comparator.comparing(MetadataUtil::getTimestamp));
+                if (optional.isPresent()) {
+                    return MetadataUtil.getValue(optional.get());
+                }
+            }
+            return null;
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public List<String> getChildrenKeys(final String key) {
+        try {
+            Stream<String> concatKeys = Stream.empty();
+            for (RegisterMetadata registerMetadata : RegisterMetadata.values()) {
+                Stream<String> keys = findExisted(registerMetadata.isEphemeral()).stream()
+                        .map(instance -> {
+                            String fullPath = MetadataUtil.getKey(instance);
+                            if (fullPath.startsWith(key + PATH_SEPARATOR)) {
+                                String pathWithoutPrefix = fullPath.substring((key + PATH_SEPARATOR).length());
+                                return pathWithoutPrefix.contains(PATH_SEPARATOR) ? pathWithoutPrefix.substring(0, pathWithoutPrefix.indexOf(PATH_SEPARATOR)) : pathWithoutPrefix;
+                            }
+                            return null;
+                        }).filter(Objects::nonNull);
+                concatKeys = Stream.concat(concatKeys, keys);
+            }
+            return concatKeys.distinct().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    @Override
+    public void persist(final String key, final String value) {
+        try {
+            if (Objects.isNull(value)) {
+                throw new IllegalArgumentException("Value cannot be null");
+            }
+            Optional<Instance> optional = findExisted(key, false).stream().max(Comparator.comparing(MetadataUtil::getTimestamp));
+            if (optional.isPresent()) {
+                update(optional.get(), value);
+            } else {
+                put(key, value, false);
+            }
+            // CHECKSTYLE:OFF
+        } catch (Exception cause) {
+            // CHECKSTYLE:ON
+            throw new ClusterPersistRepositoryException(cause);
+        }
+    }
+    
+    private void put(final String key, final String value, final boolean ephemeral) throws NacosException, InterruptedException {
+        final List<KeyValue> keyValues = buildParentPath(key);
+        RegisterMetadata registerMetadata = RegisterMetadata.of(ephemeral);
+        Instance instance = new Instance();
+        instance.setIp(nacosProps.getValue(NacosPropertyKey.CLUSTER_IP));
+        instance.setPort(registerMetadata.getPort());
+        instance.setEphemeral(ephemeral);
+        Map<String, String> metadataMap = new HashMap<>(5, 1);
+        if (ephemeral) {
+            fillEphemeralMetadata(metadataMap);
+        }
+        metadataMap.put(key, value);
+        metadataMap.put(MetadataUtil.UTC_ZONE_OFFSET.toString(), String.valueOf(MetadataUtil.getTimestamp()));
+        instance.setMetadata(metadataMap);
+        client.registerInstance(registerMetadata.name(), instance);
+        keyValues.add(new KeyValue(key, value, ephemeral));
+        waitValue(keyValues);
+    }
+    
+    private List<KeyValue> buildParentPath(final String key) throws NacosException {
+        List<KeyValue> keyValues = new LinkedList<>();
+        StringBuilder parentPath = new StringBuilder();
+        String[] partPath = key.split(PATH_SEPARATOR);
+        for (int index = 1; index < partPath.length - 1; index++) {
+            String path = parentPath.append(PATH_SEPARATOR).append(partPath[index]).toString();
+            if (findExisted(path, false).isEmpty()) {
+                keyValues.addAll(build(path));
+            }
+        }
+        return keyValues;
+    }
+    
+    private List<KeyValue> build(final String key) throws NacosException {
+        List<KeyValue> keyValues = new LinkedList<>();
+        if (findExisted(key, RegisterMetadata.PERSISTENT.isEphemeral()).isEmpty()) {
+            Instance instance = new Instance();
+            instance.setIp(nacosProps.getValue(NacosPropertyKey.CLUSTER_IP));
+            instance.setPort(RegisterMetadata.PERSISTENT.getPort());
+            instance.setEphemeral(false);
+            Map<String, String> metadataMap = new HashMap<>(2, 1);
+            metadataMap.put(key, MetadataUtil.EMPTY);
+            metadataMap.put(MetadataUtil.UTC_ZONE_OFFSET.toString(), String.valueOf(MetadataUtil.getTimestamp()));
+            instance.setMetadata(metadataMap);
+            client.registerInstance(RegisterMetadata.PERSISTENT.name(), instance);
+            keyValues.add(new KeyValue(key, MetadataUtil.EMPTY, false));
+        }
+        return keyValues;

Review Comment:
   Please name as `result` for return value



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/WatchData.java:
##########
@@ -0,0 +1,39 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.Data;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+
+/**
+ * Watch data.
+ */
+@Data

Review Comment:
   Is it necessary to use @DaTa here?



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/entity/RegisterMetadata.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.entity;
+
+import lombok.Getter;
+import lombok.RequiredArgsConstructor;
+import lombok.Setter;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.listener.NamingEventListener;
+
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Stream;
+
+/**
+ * Register metadata.
+ */
+@RequiredArgsConstructor
+public enum RegisterMetadata {
+    
+    /**
+     * persistent.
+     */
+    PERSISTENT(false),
+    
+    /**
+     * ephemeral.
+     */
+    EPHEMERAL(true);
+    
+    @Setter
+    private AtomicInteger port;

Review Comment:
   How about use Constructor to init the fields?



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/NamingEventListener.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.listener.Event;
+import com.alibaba.nacos.api.naming.listener.EventListener;
+import com.alibaba.nacos.api.naming.listener.NamingEvent;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Naming event listener.
+ */
+@RequiredArgsConstructor
+public class NamingEventListener implements EventListener {
+    
+    private Map<String, Instance> preInstances = new HashMap<>();
+    
+    private final Map<String, DataChangedEventListener> prefixListenerMap;
+    
+    @Override
+    public void onEvent(final Event event) {
+        if (event instanceof NamingEvent) {
+            NamingEvent namingEvent = (NamingEvent) event;
+            List<Instance> instances = namingEvent.getInstances().stream().sorted(Comparator.comparing(MetadataUtil::getKey)).collect(Collectors.toList());
+            List<WatchData> watchDataList = new LinkedList<>();
+            instances.forEach(instance -> prefixListenerMap.forEach((prefixPath, listener) -> {
+                String key = MetadataUtil.getKey(instance);
+                if (key.startsWith(prefixPath)) {
+                    Instance preInstance = preInstances.remove(key);
+                    WatchData watchData = new WatchData(key, preInstance, instance, listener);
+                    watchDataList.add(watchData);
+                }
+            }));
+            preInstances.values().stream().sorted(Comparator.comparing(MetadataUtil::getKey).reversed()).forEach(instance -> prefixListenerMap.forEach((prefixPath, listener) -> {
+                String key = MetadataUtil.getKey(instance);
+                if (key.startsWith(prefixPath)) {
+                    WatchData watchData = new WatchData(key, instance, null, listener);
+                    watchDataList.add(watchData);
+                }
+            }));
+            watchDataList.forEach(watchData -> {
+                String key = watchData.getKey();
+                Instance preInstance = watchData.getPreInstance();
+                Instance instance = watchData.getInstance();
+                DataChangedEventListener listener = watchData.getListener();
+                DataChangedEvent.Type changedType = getEventChangedType(preInstance, instance);
+                switch (changedType) {
+                    case ADDED:
+                    case UPDATED:
+                        listener.onChange(new DataChangedEvent(key, MetadataUtil.getValue(instance), changedType));
+                        break;
+                    case DELETED:
+                        listener.onChange(new DataChangedEvent(key, MetadataUtil.getValue(preInstance), changedType));
+                        break;
+                    default:
+                }
+            });
+            setPreInstances(instances);
+        }
+    }
+    
+    private DataChangedEvent.Type getEventChangedType(final Instance preInstance, final Instance instance) {
+        DataChangedEvent.Type type;
+        if (Objects.isNull(preInstance) && Objects.nonNull(instance)) {
+            type = DataChangedEvent.Type.ADDED;
+        } else if (Objects.nonNull(preInstance) && Objects.nonNull(instance)
+                && MetadataUtil.getTimestamp(preInstance) != MetadataUtil.getTimestamp(instance)) {
+            type = DataChangedEvent.Type.UPDATED;
+        } else if (Objects.nonNull(preInstance) && Objects.isNull(instance)) {
+            type = DataChangedEvent.Type.DELETED;
+        } else {
+            return DataChangedEvent.Type.IGNORED;
+        }
+        return type;

Review Comment:
   Please name as `result` for return value



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/utils/MetadataUtil.java:
##########
@@ -0,0 +1,78 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.utils;
+
+import com.alibaba.nacos.api.exception.NacosException;
+import com.alibaba.nacos.api.naming.PreservedMetadataKeys;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.SneakyThrows;
+
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+
+/**
+ * Metadata util.
+ */
+public class MetadataUtil {

Review Comment:
   Please add final if class does not design for extension



##########
shardingsphere-mode/shardingsphere-mode-type/shardingsphere-cluster-mode/shardingsphere-cluster-mode-repository/shardingsphere-cluster-mode-repository-provider/shardingsphere-cluster-mode-repository-nacos/src/main/java/org/apache/shardingsphere/mode/repository/cluster/nacos/listener/NamingEventListener.java:
##########
@@ -0,0 +1,129 @@
+/*
+ * 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.shardingsphere.mode.repository.cluster.nacos.listener;
+
+import com.alibaba.nacos.api.naming.listener.Event;
+import com.alibaba.nacos.api.naming.listener.EventListener;
+import com.alibaba.nacos.api.naming.listener.NamingEvent;
+import com.alibaba.nacos.api.naming.pojo.Instance;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEvent;
+import org.apache.shardingsphere.mode.repository.cluster.listener.DataChangedEventListener;
+import org.apache.shardingsphere.mode.repository.cluster.nacos.utils.MetadataUtil;
+
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+
+/**
+ * Naming event listener.
+ */
+@RequiredArgsConstructor
+public class NamingEventListener implements EventListener {
+    
+    private Map<String, Instance> preInstances = new HashMap<>();
+    
+    private final Map<String, DataChangedEventListener> prefixListenerMap;
+    
+    @Override
+    public void onEvent(final Event event) {
+        if (event instanceof NamingEvent) {
+            NamingEvent namingEvent = (NamingEvent) event;
+            List<Instance> instances = namingEvent.getInstances().stream().sorted(Comparator.comparing(MetadataUtil::getKey)).collect(Collectors.toList());
+            List<WatchData> watchDataList = new LinkedList<>();
+            instances.forEach(instance -> prefixListenerMap.forEach((prefixPath, listener) -> {
+                String key = MetadataUtil.getKey(instance);
+                if (key.startsWith(prefixPath)) {
+                    Instance preInstance = preInstances.remove(key);
+                    WatchData watchData = new WatchData(key, preInstance, instance, listener);
+                    watchDataList.add(watchData);
+                }
+            }));
+            preInstances.values().stream().sorted(Comparator.comparing(MetadataUtil::getKey).reversed()).forEach(instance -> prefixListenerMap.forEach((prefixPath, listener) -> {
+                String key = MetadataUtil.getKey(instance);
+                if (key.startsWith(prefixPath)) {
+                    WatchData watchData = new WatchData(key, instance, null, listener);
+                    watchDataList.add(watchData);
+                }
+            }));
+            watchDataList.forEach(watchData -> {
+                String key = watchData.getKey();
+                Instance preInstance = watchData.getPreInstance();
+                Instance instance = watchData.getInstance();
+                DataChangedEventListener listener = watchData.getListener();
+                DataChangedEvent.Type changedType = getEventChangedType(preInstance, instance);
+                switch (changedType) {
+                    case ADDED:
+                    case UPDATED:
+                        listener.onChange(new DataChangedEvent(key, MetadataUtil.getValue(instance), changedType));
+                        break;
+                    case DELETED:
+                        listener.onChange(new DataChangedEvent(key, MetadataUtil.getValue(preInstance), changedType));
+                        break;
+                    default:
+                }
+            });
+            setPreInstances(instances);
+        }
+    }
+    
+    private DataChangedEvent.Type getEventChangedType(final Instance preInstance, final Instance instance) {
+        DataChangedEvent.Type type;
+        if (Objects.isNull(preInstance) && Objects.nonNull(instance)) {
+            type = DataChangedEvent.Type.ADDED;
+        } else if (Objects.nonNull(preInstance) && Objects.nonNull(instance)
+                && MetadataUtil.getTimestamp(preInstance) != MetadataUtil.getTimestamp(instance)) {
+            type = DataChangedEvent.Type.UPDATED;
+        } else if (Objects.nonNull(preInstance) && Objects.isNull(instance)) {
+            type = DataChangedEvent.Type.DELETED;
+        } else {
+            return DataChangedEvent.Type.IGNORED;
+        }
+        return type;
+    }
+    
+    /**
+     * Update preInstances.
+     * @param instances instances

Review Comment:
   Please keep blank line between java doc and @param



-- 
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: notifications-unsubscribe@shardingsphere.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org