You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@seata.apache.org by xi...@apache.org on 2025/09/12 02:32:38 UTC
(incubator-seata) branch gsoc-2025-meta-registry updated: feature: Support metadata-based registration and discovery in Seata (#7533)
This is an automated email from the ASF dual-hosted git repository.
xingfudeshi pushed a commit to branch gsoc-2025-meta-registry
in repository https://gitbox.apache.org/repos/asf/incubator-seata.git
The following commit(s) were added to refs/heads/gsoc-2025-meta-registry by this push:
new e6c3a0e580 feature: Support metadata-based registration and discovery in Seata (#7533)
e6c3a0e580 is described below
commit e6c3a0e58085e50b1977df3e4c4c23da5d4b1443
Author: YoWuwuuuw <22...@qq.com>
AuthorDate: Fri Sep 12 10:32:33 2025 +0800
feature: Support metadata-based registration and discovery in Seata (#7533)
---
changes/en-us/2.x.md | 1 +
changes/zh-cn/2.x.md | 2 +
.../seata/common/metadata/ServiceInstance.java | 135 ++++++++
.../seata/common/metadata/ServiceInstanceTest.java | 123 +++++++
.../rpc/netty/AbstractNettyRemotingClient.java | 13 +-
.../core/rpc/netty/NettyClientChannelManager.java | 35 +-
.../seata/core/rpc/netty/NettyServerBootstrap.java | 14 +-
.../registry/consul/ConsulRegistryServiceImpl.java | 26 +-
.../consul/ConsulRegistryServiceImplMockTest.java | 7 +-
.../loadbalance/ConsistentHashLoadBalance.java | 25 +-
.../loadbalance/LeastActiveLoadBalance.java | 6 +-
.../seata/discovery/loadbalance/LoadBalance.java | 5 +-
.../discovery/loadbalance/LoadBalanceFactory.java | 11 +-
.../discovery/loadbalance/RandomLoadBalance.java | 1 -
.../loadbalance/RoundRobinLoadBalance.java | 1 -
.../loadbalance/WeightedRandomLoadBalance.java | 140 ++++++++
.../discovery/loadbalance/XIDLoadBalance.java | 6 +-
.../registry/FileRegistryServiceImpl.java | 21 +-
.../discovery/registry/RegistryHeartBeats.java | 2 +-
.../seata/discovery/registry/RegistryProvider.java | 1 +
.../seata/discovery/registry/RegistryService.java | 129 ++++---
.../seata/discovery/registry/RegistryType.java | 1 -
....apache.seata.discovery.loadbalance.LoadBalance | 3 +-
.../seata/config/ConfigurationFactoryTest.java | 43 ---
.../loadbalance/LoadBalanceFactoryTest.java | 124 ++-----
.../discovery/loadbalance/LoadBalanceTest.java | 319 ++++++++++++-----
...Provider.java => FileRegistryProviderTest.java} | 20 +-
.../registry/FileRegistryServiceImplTest.java | 161 +++++++++
.../registry/MultiRegistryFactoryTest.java | 1 +
.../{ => mock}/MockNacosRegistryProvider.java | 4 +-
.../{ => mock}/MockNacosRegistryService.java | 12 +-
...pache.seata.discovery.registry.RegistryProvider | 2 +-
.../src/test/resources/file.conf | 9 +
.../src/test/resources/registry.conf | 59 ----
.../custom/CustomRegistryServiceForTest.java | 12 +-
.../registry/etcd3/EtcdRegistryServiceImpl.java | 25 +-
.../etcd3/EtcdRegistryServiceImplMockTest.java | 12 +-
.../etcd3/EtcdRegistryServiceImplTest.java | 19 +-
.../registry/eureka/EurekaRegistryServiceImpl.java | 35 +-
.../eureka/EurekaRegistryServiceImplTest.java | 18 +-
.../src/test/resources/registry.conf | 57 ---
.../registry/nacos/NacosRegistryServiceImpl.java | 53 +--
.../nacos/NacosRegistryServiceImplTest.java | 1 -
.../src/test/resources/registry.conf | 75 ----
.../registry/namingserver/NamingListener.java | 8 +-
.../namingserver/NamingRegistryException.java | 5 +-
.../namingserver/NamingserverRegistryProvider.java | 9 +
.../NamingserverRegistryServiceImpl.java | 267 +++++++-------
.../NamingserverRegistryProviderTest.java} | 19 +-
.../NamingserverRegistryServiceImplMockTest.java | 276 +++++++++++++++
.../NamingserverRegistryServiceImplTest.java | 385 +++++++--------------
.../src/test/resources/registry.conf | 94 +----
.../registry/raft/RaftRegistryServiceImpl.java | 64 ++--
.../src/test/resources/registry.conf | 9 +-
.../registry/redis/RedisRegistryServiceImpl.java | 38 +-
.../redis/RedisRegisterServiceImplTest.java | 21 +-
.../registry/sofa/SofaRegistryServiceImpl.java | 34 +-
.../registry/zk/ZookeeperRegisterServiceImpl.java | 40 ++-
.../zk/ZookeeperRegisterServiceImplTest.java | 60 ++--
.../src/test/resources/registry.conf | 66 +---
.../server/cluster/raft/RaftServerManager.java | 6 +-
.../raft/store/RaftVGroupMappingStoreManager.java | 7 +-
.../server/store/VGroupMappingStoreManager.java | 6 +-
.../main/resources/application.raft.example.yml | 2 +
64 files changed, 1821 insertions(+), 1364 deletions(-)
diff --git a/changes/en-us/2.x.md b/changes/en-us/2.x.md
index ff94142587..e421c9ae99 100644
--- a/changes/en-us/2.x.md
+++ b/changes/en-us/2.x.md
@@ -23,6 +23,7 @@ Add changes here for all PR submitted to the 2.x branch.
- [[#7261](https://github.com/apache/incubator-seata/pull/7261)] enforce account initialization and disable default credentials
- [[#7451](https://github.com/apache/incubator-seata/pull/7451)] seata-server supports the HTTP/2 protocol
- [[#7496](https://github.com/apache/incubator-seata/pull/7496)] add oceanbase oracle support
+- [[#7533](https://github.com/apache/incubator-seata/pull/7533)] support metadata-based registration and discovery, support namingserver type
### bugfix:
diff --git a/changes/zh-cn/2.x.md b/changes/zh-cn/2.x.md
index 721d3870a9..018481b450 100644
--- a/changes/zh-cn/2.x.md
+++ b/changes/zh-cn/2.x.md
@@ -23,6 +23,8 @@
- [[#7261](https://github.com/apache/incubator-seata/pull/7261)] 强制进行账户初始化并禁用默认凭据
- [[#7451](https://github.com/apache/incubator-seata/pull/7451)] seata-server支持HTTP/2协议
- [[#7496](https://github.com/apache/incubator-seata/pull/7496)] 添加对oceanbase数据库oracle模式的支持
+- [[#7533](https://github.com/apache/incubator-seata/pull/7533)] 支持元数据注册与发现能力并支持namingserver类型
+
### bugfix:
diff --git a/common/src/main/java/org/apache/seata/common/metadata/ServiceInstance.java b/common/src/main/java/org/apache/seata/common/metadata/ServiceInstance.java
new file mode 100644
index 0000000000..06b8bc68de
--- /dev/null
+++ b/common/src/main/java/org/apache/seata/common/metadata/ServiceInstance.java
@@ -0,0 +1,135 @@
+/*
+ * 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.seata.common.metadata;
+
+import org.apache.seata.common.util.NetUtil;
+
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/**
+ * entity for packaging inetSocketAddress and metadata for loadBalance
+ */
+public class ServiceInstance {
+ private InetSocketAddress address;
+ private Map<String, Object> metadata;
+
+ public ServiceInstance(InetSocketAddress address, Map<String, Object> metadata) {
+ this.address = address;
+ this.metadata = metadata;
+ }
+
+ public ServiceInstance(Instance instance) {
+ this.address = new InetSocketAddress(
+ instance.getTransaction().getHost(), instance.getTransaction().getPort());
+ this.metadata = instance.getMetadata();
+ }
+
+ public ServiceInstance(InetSocketAddress address) {
+ this.address = address;
+ }
+
+ public InetSocketAddress getAddress() {
+ return address;
+ }
+
+ public void setAddress(InetSocketAddress address) {
+ this.address = address;
+ }
+
+ public Map<String, Object> getMetadata() {
+ return metadata;
+ }
+
+ public void setMetadata(Map<String, Object> metadata) {
+ this.metadata = metadata;
+ }
+
+ /**
+ * Converts a list of InetSocketAddress to a list of ServiceInstance.
+ * @param addresses list of InetSocketAddress
+ * @return list of ServiceInstance
+ */
+ public static List<ServiceInstance> convertToServiceInstanceSet(List<InetSocketAddress> addresses) {
+ List<ServiceInstance> serviceInstances = new ArrayList<>();
+ if (addresses != null && !addresses.isEmpty()) {
+ for (InetSocketAddress address : addresses) {
+ NetUtil.validAddress(address);
+ serviceInstances.add(new ServiceInstance(address, null));
+ }
+ }
+ return serviceInstances;
+ }
+
+ /**
+ * Converts a set of InetSocketAddress to a set of ServiceInstance in RedisRegistryServiceImpl.
+ * @param addresses set of InetSocketAddress
+ * @return set of ServiceInstance
+ */
+ public static Set<ServiceInstance> convertToServiceInstanceSet(Set<InetSocketAddress> addresses) {
+ Set<ServiceInstance> serviceInstances = new HashSet<>();
+ if (addresses != null && !addresses.isEmpty()) {
+ for (InetSocketAddress address : addresses) {
+ NetUtil.validAddress(address);
+ serviceInstances.add(new ServiceInstance(address, null));
+ }
+ }
+ return serviceInstances;
+ }
+
+ /**
+ * Creates a ServiceInstance from an InetSocketAddress and a Map<String, String> of metadata.
+ * @param address the InetSocketAddress
+ * @param stringMap the map of string metadata
+ * @return a new ServiceInstance
+ */
+ public static ServiceInstance fromStringMap(InetSocketAddress address, Map<String, String> stringMap) {
+ Map<String, Object> metadata = new HashMap<>();
+ if (stringMap != null) {
+ metadata.putAll(stringMap);
+ }
+ return new ServiceInstance(address, metadata);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ ServiceInstance that = (ServiceInstance) o;
+ return Objects.equals(address, that.address) && Objects.equals(metadata, that.metadata);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(address, metadata);
+ }
+
+ @Override
+ public String toString() {
+ return "ServiceInstance{" + "address=" + address + ", metadata=" + metadata + '}';
+ }
+}
diff --git a/common/src/test/java/org/apache/seata/common/metadata/ServiceInstanceTest.java b/common/src/test/java/org/apache/seata/common/metadata/ServiceInstanceTest.java
new file mode 100644
index 0000000000..a733b25cab
--- /dev/null
+++ b/common/src/test/java/org/apache/seata/common/metadata/ServiceInstanceTest.java
@@ -0,0 +1,123 @@
+/*
+ * 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.seata.common.metadata;
+
+import org.junit.jupiter.api.Test;
+
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+public class ServiceInstanceTest {
+
+ private final InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 8091);
+ private final InetSocketAddress address2 = new InetSocketAddress("127.0.0.1", 8092);
+
+ @Test
+ public void testConstructorAndGetters() {
+ Map<String, Object> metadata = new HashMap<>();
+ metadata.put("key1", "value1");
+
+ ServiceInstance instance1 = new ServiceInstance(address1, metadata);
+
+ assertEquals(address1, instance1.getAddress());
+ assertEquals(metadata, instance1.getMetadata());
+
+ Instance instance = Instance.getInstance();
+ instance.setTransaction(new Node.Endpoint("127.0.0.1", 8093));
+
+ ServiceInstance instance2 = new ServiceInstance(Instance.getInstance());
+
+ assertEquals(
+ Instance.getInstance().getTransaction().getHost(),
+ instance2.getAddress().getAddress().getHostAddress());
+ assertEquals(
+ Instance.getInstance().getTransaction().getPort(),
+ instance2.getAddress().getPort());
+
+ instance.setTransaction(null); // clean up after test
+ }
+
+ @Test
+ public void testConvertToServiceInstanceList() {
+ List<InetSocketAddress> addresses = new ArrayList<>();
+ addresses.add(address1);
+ addresses.add(address2);
+
+ List<ServiceInstance> serviceInstances = ServiceInstance.convertToServiceInstanceSet(addresses);
+
+ assertEquals(2, serviceInstances.size());
+ assertEquals(address1, serviceInstances.get(0).getAddress());
+ assertEquals(address2, serviceInstances.get(1).getAddress());
+ }
+
+ @Test
+ public void testConvertToServiceInstanceSet() {
+ Set<InetSocketAddress> addresses = new HashSet<>();
+ addresses.add(address1);
+ addresses.add(address2);
+
+ Set<ServiceInstance> serviceInstances = ServiceInstance.convertToServiceInstanceSet(addresses);
+
+ assertEquals(2, serviceInstances.size());
+ }
+
+ @Test
+ public void testSetAddressAndSetMetadata() {
+ ServiceInstance instance = new ServiceInstance(address1);
+ instance.setAddress(address2);
+ instance.setMetadata(new HashMap<>());
+
+ assertEquals(address2, instance.getAddress());
+ assertNotNull(instance.getMetadata());
+ }
+
+ @Test
+ public void testFromStringMap() {
+ Map<String, String> stringMap = new HashMap<>();
+ stringMap.put("stringKey", "stringValue");
+
+ ServiceInstance instance = ServiceInstance.fromStringMap(address1, stringMap);
+
+ assertEquals(address1, instance.getAddress());
+ assertNotNull(instance.getMetadata());
+ assertEquals("stringValue", instance.getMetadata().get("stringKey"));
+ }
+
+ @Test
+ public void testEqualsAndToString() {
+ ServiceInstance instance1 = new ServiceInstance(address1);
+ ServiceInstance instance2 = new ServiceInstance(address1);
+ ServiceInstance instance3 = new ServiceInstance(address2);
+
+ assertTrue(instance1.equals(instance2));
+ assertTrue(instance1.equals(instance1));
+ assertFalse(instance1.equals(instance3));
+ assertFalse(instance1.equals("string"));
+
+ assertTrue(instance1.toString().contains("8091"));
+ }
+}
diff --git a/core/src/main/java/org/apache/seata/core/rpc/netty/AbstractNettyRemotingClient.java b/core/src/main/java/org/apache/seata/core/rpc/netty/AbstractNettyRemotingClient.java
index 28ff56baef..c227570cb0 100644
--- a/core/src/main/java/org/apache/seata/core/rpc/netty/AbstractNettyRemotingClient.java
+++ b/core/src/main/java/org/apache/seata/core/rpc/netty/AbstractNettyRemotingClient.java
@@ -27,6 +27,7 @@ import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.seata.common.exception.FrameworkErrorCode;
import org.apache.seata.common.exception.FrameworkException;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
@@ -287,9 +288,9 @@ public abstract class AbstractNettyRemotingClient extends AbstractNettyRemoting
InetSocketAddress address = null;
try {
@SuppressWarnings("unchecked")
- List<InetSocketAddress> inetSocketAddressList =
+ List<ServiceInstance> serviceInstances =
RegistryFactory.getInstance().aliveLookup(transactionServiceGroup);
- address = this.doSelect(inetSocketAddressList, msg);
+ address = this.doSelect(serviceInstances, msg);
} catch (Exception ex) {
LOGGER.error("Select the address failed: {}", ex.getMessage());
}
@@ -299,12 +300,14 @@ public abstract class AbstractNettyRemotingClient extends AbstractNettyRemoting
return NetUtil.toStringAddress(address);
}
- protected InetSocketAddress doSelect(List<InetSocketAddress> list, Object msg) throws Exception {
+ protected InetSocketAddress doSelect(List<ServiceInstance> list, Object msg) throws Exception {
if (CollectionUtils.isNotEmpty(list)) {
if (list.size() > 1) {
- return LoadBalanceFactory.getInstance().select(list, getXid(msg));
+ return LoadBalanceFactory.getInstance()
+ .select(list, getXid(msg))
+ .getAddress();
} else {
- return list.get(0);
+ return list.get(0).getAddress();
}
}
return null;
diff --git a/core/src/main/java/org/apache/seata/core/rpc/netty/NettyClientChannelManager.java b/core/src/main/java/org/apache/seata/core/rpc/netty/NettyClientChannelManager.java
index 02cc6f8c3a..1a6733e6fb 100644
--- a/core/src/main/java/org/apache/seata/core/rpc/netty/NettyClientChannelManager.java
+++ b/core/src/main/java/org/apache/seata/core/rpc/netty/NettyClientChannelManager.java
@@ -21,6 +21,7 @@ import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.apache.seata.common.ConfigurationKeys;
import org.apache.seata.common.exception.FrameworkErrorCode;
import org.apache.seata.common.exception.FrameworkException;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -31,7 +32,6 @@ import org.apache.seata.discovery.registry.RegistryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -189,7 +189,7 @@ class NettyClientChannelManager {
* @param failFast
*/
void doReconnect(String transactionServiceGroup, boolean failFast) {
- List<String> availList;
+ List<ServiceInstance> availList;
try {
availList = getAvailServerList(transactionServiceGroup);
} catch (Exception e) {
@@ -234,16 +234,16 @@ class NettyClientChannelManager {
* @param availList avail list
* @param transactionServiceGroup transaction service group
*/
- void doReconnect(List<String> availList, String transactionServiceGroup) {
- Set<String> channelAddress = new HashSet<>(availList.size());
- Map<String, Exception> failedMap = new HashMap<>();
+ void doReconnect(List<ServiceInstance> availList, String transactionServiceGroup) {
+ Set<ServiceInstance> channelAddress = new HashSet<>(availList.size());
+ Map<ServiceInstance, Exception> failedMap = new HashMap<>();
try {
- for (String serverAddress : availList) {
+ for (ServiceInstance serviceInstance : availList) {
try {
- acquireChannel(serverAddress);
- channelAddress.add(serverAddress);
+ acquireChannel(NetUtil.toStringAddress(serviceInstance.getAddress()));
+ channelAddress.add(serviceInstance);
} catch (Exception e) {
- failedMap.put(serverAddress, e);
+ failedMap.put(serviceInstance, e);
}
}
if (failedMap.size() > 0) {
@@ -272,12 +272,8 @@ class NettyClientChannelManager {
}
} finally {
if (CollectionUtils.isNotEmpty(channelAddress)) {
- List<InetSocketAddress> aliveAddress = new ArrayList<>(channelAddress.size());
- for (String address : channelAddress) {
- String[] array = NetUtil.splitIPPortStr(address);
- aliveAddress.add(new InetSocketAddress(array[0], Integer.parseInt(array[1])));
- }
- RegistryFactory.getInstance().refreshAliveLookup(transactionServiceGroup, aliveAddress);
+ RegistryFactory.getInstance()
+ .refreshAliveLookup(transactionServiceGroup, new ArrayList<>(channelAddress));
} else {
RegistryFactory.getInstance().refreshAliveLookup(transactionServiceGroup, Collections.emptyList());
}
@@ -315,14 +311,15 @@ class NettyClientChannelManager {
return channelFromPool;
}
- private List<String> getAvailServerList(String transactionServiceGroup) throws Exception {
- List<InetSocketAddress> availInetSocketAddressList =
+ private List<ServiceInstance> getAvailServerList(String transactionServiceGroup) throws Exception {
+ @SuppressWarnings("unchecked")
+ List<ServiceInstance> availServiceInstanceList =
RegistryFactory.getInstance().lookup(transactionServiceGroup);
- if (CollectionUtils.isEmpty(availInetSocketAddressList)) {
+ if (CollectionUtils.isEmpty(availServiceInstanceList)) {
return Collections.emptyList();
}
- return availInetSocketAddressList.stream().map(NetUtil::toStringAddress).collect(Collectors.toList());
+ return availServiceInstanceList;
}
private Channel getExistAliveChannel(Channel rmChannel, String serverAddress) {
diff --git a/core/src/main/java/org/apache/seata/core/rpc/netty/NettyServerBootstrap.java b/core/src/main/java/org/apache/seata/core/rpc/netty/NettyServerBootstrap.java
index f6e99ffef2..53a3daa172 100644
--- a/core/src/main/java/org/apache/seata/core/rpc/netty/NettyServerBootstrap.java
+++ b/core/src/main/java/org/apache/seata/core/rpc/netty/NettyServerBootstrap.java
@@ -31,6 +31,7 @@ import org.apache.seata.common.ConfigurationKeys;
import org.apache.seata.common.XID;
import org.apache.seata.common.metadata.Instance;
import org.apache.seata.common.metadata.Node;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.config.ConfigurationFactory;
import org.apache.seata.core.protocol.detector.Http2Detector;
@@ -197,10 +198,13 @@ public class NettyServerBootstrap implements RemotingBootstrap {
Instance instance = Instance.getInstance();
// Lines 177-180 are just for compatibility with test cases
if (instance.getTransaction() == null) {
- Instance.getInstance().setTransaction(new Node.Endpoint(XID.getIpAddress(), XID.getPort(), "netty"));
+ instance.setTransaction(new Node.Endpoint(XID.getIpAddress(), XID.getPort(), "netty"));
}
+ InetSocketAddress inetSocketAddress = new InetSocketAddress(
+ instance.getTransaction().getHost(),
+ instance.getTransaction().getPort());
for (RegistryService<?> registryService : MultiRegistryFactory.getInstances()) {
- registryService.register(Instance.getInstance());
+ registryService.register(new ServiceInstance(inetSocketAddress, instance.getMetadata()));
}
initialized.set(true);
} catch (SocketException se) {
@@ -217,8 +221,12 @@ public class NettyServerBootstrap implements RemotingBootstrap {
LOGGER.info("Shutting server down, the listen port: {}", XID.getPort());
}
if (initialized.get()) {
+ Instance instance = Instance.getInstance();
+ InetSocketAddress inetSocketAddress = new InetSocketAddress(
+ instance.getTransaction().getHost(),
+ instance.getTransaction().getPort());
for (RegistryService registryService : MultiRegistryFactory.getInstances()) {
- registryService.unregister(Instance.getInstance());
+ registryService.unregister(new ServiceInstance(inetSocketAddress, instance.getMetadata()));
registryService.close();
}
// wait a few seconds for server transport
diff --git a/discovery/seata-discovery-consul/src/main/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImpl.java b/discovery/seata-discovery-consul/src/main/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImpl.java
index d7a8774f35..25bdd93a4d 100644
--- a/discovery/seata-discovery-consul/src/main/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImpl.java
+++ b/discovery/seata-discovery-consul/src/main/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImpl.java
@@ -22,6 +22,7 @@ import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.agent.model.NewService;
import com.ecwid.consul.v1.health.HealthServicesRequest;
import com.ecwid.consul.v1.health.model.HealthService;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -65,7 +66,7 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
private static final String FILE_CONFIG_KEY_PREFIX =
FILE_ROOT_REGISTRY + FILE_CONFIG_SPLIT_CHAR + REGISTRY_TYPE + FILE_CONFIG_SPLIT_CHAR;
- private ConcurrentMap<String, List<InetSocketAddress>> clusterAddressMap;
+ private ConcurrentMap<String, List<ServiceInstance>> clusterAddressMap;
private ConcurrentMap<String, Set<ConsulListener>> listenerMap;
private ExecutorService notifierExecutor;
private ConcurrentMap<String, ConsulNotifier> notifiers;
@@ -123,8 +124,10 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
+
doRegister(address);
RegistryHeartBeats.addHeartBeat(REGISTRY_TYPE, address, this::doRegister);
}
@@ -134,13 +137,14 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
getConsulClient().agentServiceDeregister(createServiceId(address), getAclToken());
}
@Override
- public void subscribe(String cluster, ConsulListener listener) throws Exception {
+ public void subscribe(String cluster, ConsulListener listener) {
// 1.add listener to subscribe list
listenerMap.computeIfAbsent(cluster, key -> new HashSet<>()).add(listener);
// 2.get healthy services
@@ -153,7 +157,7 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
}
@Override
- public void unsubscribe(String cluster, ConsulListener listener) throws Exception {
+ public void unsubscribe(String cluster, ConsulListener listener) {
// 1.remove notifier for the cluster
ConsulNotifier notifier = notifiers.remove(cluster);
// 2.stop the notifier
@@ -161,7 +165,7 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) {
transactionServiceGroup = key;
final String cluster = getServiceGroup(key);
if (cluster == null) {
@@ -171,7 +175,7 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
return lookupByCluster(cluster);
}
- private List<InetSocketAddress> lookupByCluster(String cluster) throws Exception {
+ private List<ServiceInstance> lookupByCluster(String cluster) {
if (!listenerMap.containsKey(cluster)) {
// 1.refresh cluster
refreshCluster(cluster);
@@ -314,14 +318,14 @@ public class ConsulRegistryServiceImpl implements RegistryService<ConsulListener
return;
}
- List<InetSocketAddress> addresses = services.stream()
+ List<ServiceInstance> instances = ServiceInstance.convertToServiceInstanceSet(services.stream()
.map(HealthService::getService)
.map(service -> new InetSocketAddress(service.getAddress(), service.getPort()))
- .collect(Collectors.toList());
+ .collect(Collectors.toList()));
- clusterAddressMap.put(cluster, addresses);
+ clusterAddressMap.put(cluster, instances);
- removeOfflineAddressesIfNecessary(transactionServiceGroup, cluster, addresses);
+ removeOfflineAddressesIfNecessary(transactionServiceGroup, cluster, instances);
}
/**
diff --git a/discovery/seata-discovery-consul/src/test/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImplMockTest.java b/discovery/seata-discovery-consul/src/test/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImplMockTest.java
index d5a15b0844..39738c9efa 100644
--- a/discovery/seata-discovery-consul/src/test/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImplMockTest.java
+++ b/discovery/seata-discovery-consul/src/test/java/org/apache/seata/discovery/registry/consul/ConsulRegistryServiceImplMockTest.java
@@ -20,6 +20,7 @@ import com.ecwid.consul.transport.RawResponse;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.health.model.HealthService;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
import org.apache.seata.config.exception.ConfigNotFoundException;
@@ -76,14 +77,14 @@ public class ConsulRegistryServiceImplMockTest {
@Order(2)
@Test
public void testRegister() throws Exception {
- InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8080));
when(client.agentServiceRegister(any())).thenReturn(null);
- service.register(inetSocketAddress);
+ service.register(serviceInstance);
verify(client).agentServiceRegister(any(), any());
when(client.agentServiceDeregister(any())).thenReturn(null);
- service.unregister(inetSocketAddress);
+ service.unregister(serviceInstance);
verify(client).agentServiceDeregister(any(), any());
}
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/ConsistentHashLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/ConsistentHashLoadBalance.java
index 765e00ba18..aa47290ec5 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/ConsistentHashLoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/ConsistentHashLoadBalance.java
@@ -37,18 +37,13 @@ import static org.apache.seata.common.DefaultValues.VIRTUAL_NODES_DEFAULT;
public class ConsistentHashLoadBalance implements LoadBalance {
/**
- * The constant LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES.
+ * The number of virtual nodes
*/
- public static final String LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES =
- LoadBalanceFactory.LOAD_BALANCE_PREFIX + "virtualNodes";
- /**
- * The constant VIRTUAL_NODES_NUM.
- */
- private static final int VIRTUAL_NODES_NUM = ConfigurationFactory.getInstance()
- .getInt(LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES, VIRTUAL_NODES_DEFAULT);
+ private static final int VIRTUAL_NODES_NUM =
+ ConfigurationFactory.getInstance().getInt("client.loadBalance.virtualNodes", VIRTUAL_NODES_DEFAULT);
/**
- * The ConsistentHashSelectorWrapper that caches a {@link ConsistentHashSelector}.
+ * Consistent hashing selector wrapper for caching selector instances
*/
private volatile ConsistentHashSelectorWrapper selectorWrapper;
@@ -66,6 +61,11 @@ public class ConsistentHashLoadBalance implements LoadBalance {
return (T) selectorWrapper.getSelector(invokers).select(xid);
}
+ /**
+ * Consistent hash selector wrapper
+ *
+ * <p>Cache selector instances and update selectors when the service instance list changes</p>
+ */
@SuppressWarnings({"rawtypes", "unchecked"})
private static final class ConsistentHashSelectorWrapper {
@@ -103,6 +103,13 @@ public class ConsistentHashLoadBalance implements LoadBalance {
}
}
+ /**
+ * Consistent hash selector
+ *
+ * <p>Maintain the mapping from virtual nodes to actual service instances and provide consistent hash selection function</p>
+ *
+ * @param <T> ServiceInstance
+ */
private static final class ConsistentHashSelector<T> {
private final SortedMap<Long, T> virtualInvokers = new TreeMap<>();
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LeastActiveLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LeastActiveLoadBalance.java
index f3d794e206..01e3e436d1 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LeastActiveLoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LeastActiveLoadBalance.java
@@ -17,6 +17,7 @@
package org.apache.seata.discovery.loadbalance;
import org.apache.seata.common.loader.LoadLevel;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.rpc.RpcStatus;
import java.util.List;
@@ -26,7 +27,6 @@ import static org.apache.seata.discovery.loadbalance.LoadBalanceFactory.LEAST_AC
/**
* The type Least Active load balance.
- *
*/
@LoadLevel(name = LEAST_ACTIVE_LOAD_BALANCE)
public class LeastActiveLoadBalance implements LoadBalance {
@@ -38,7 +38,9 @@ public class LeastActiveLoadBalance implements LoadBalance {
int leastCount = 0;
int[] leastIndexes = new int[length];
for (int i = 0; i < length; i++) {
- long active = RpcStatus.getStatus(invokers.get(i).toString()).getActive();
+ ServiceInstance serviceInstance = (ServiceInstance) invokers.get(i);
+ long active =
+ RpcStatus.getStatus(serviceInstance.getAddress().toString()).getActive();
if (leastActive == -1 || active < leastActive) {
leastActive = active;
leastCount = 1;
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalance.java
index c1435945b4..74a46b6cfa 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalance.java
@@ -20,19 +20,18 @@ import java.util.List;
/**
* The interface Load balance.
- *
*/
public interface LoadBalance {
String SPLIT = ":";
/**
- * Select t.
+ * Select ServiceInstances.
*
* @param <T> the type parameter
* @param invokers the invokers
* @param xid the xid
- * @return the t
+ * @return the ServiceInstance
* @throws Exception the exception
*/
<T> T select(List<T> invokers, String xid) throws Exception;
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactory.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactory.java
index e6b8331676..1021e77aa9 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactory.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactory.java
@@ -23,17 +23,10 @@ import static org.apache.seata.common.DefaultValues.DEFAULT_LOAD_BALANCE;
/**
* The type Load balance factory.
- *
*/
public class LoadBalanceFactory {
- private static final String CLIENT_PREFIX = "client.";
- /**
- * The constant LOAD_BALANCE_PREFIX.
- */
- public static final String LOAD_BALANCE_PREFIX = CLIENT_PREFIX + "loadBalance.";
-
- public static final String LOAD_BALANCE_TYPE = LOAD_BALANCE_PREFIX + "type";
+ public static final String LOAD_BALANCE_TYPE = "client.loadBalance.type";
public static final String RANDOM_LOAD_BALANCE = "RandomLoadBalance";
@@ -45,6 +38,8 @@ public class LoadBalanceFactory {
public static final String LEAST_ACTIVE_LOAD_BALANCE = "LeastActiveLoadBalance";
+ public static final String WEIGHTED_RANDOM_LOAD_BALANCE = "WeightedRandomLoadBalance";
+
/**
* Get instance.
*
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RandomLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RandomLoadBalance.java
index 9443c2070a..a5c63fcee8 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RandomLoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RandomLoadBalance.java
@@ -23,7 +23,6 @@ import java.util.concurrent.ThreadLocalRandom;
/**
* The type Random load balance.
- *
*/
@LoadLevel(name = LoadBalanceFactory.RANDOM_LOAD_BALANCE)
public class RandomLoadBalance implements LoadBalance {
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RoundRobinLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RoundRobinLoadBalance.java
index ecac094c18..983b2a2b6d 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RoundRobinLoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/RoundRobinLoadBalance.java
@@ -23,7 +23,6 @@ import java.util.concurrent.atomic.AtomicInteger;
/**
* The type Round robin load balance.
- *
*/
@LoadLevel(name = LoadBalanceFactory.ROUND_ROBIN_LOAD_BALANCE)
public class RoundRobinLoadBalance implements LoadBalance {
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/WeightedRandomLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/WeightedRandomLoadBalance.java
new file mode 100644
index 0000000000..6a908e9aa3
--- /dev/null
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/WeightedRandomLoadBalance.java
@@ -0,0 +1,140 @@
+/*
+ * 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.seata.discovery.loadbalance;
+
+import org.apache.seata.common.loader.EnhancedServiceLoader;
+import org.apache.seata.common.loader.LoadLevel;
+import org.apache.seata.common.metadata.ServiceInstance;
+
+import java.util.List;
+import java.util.concurrent.ThreadLocalRandom;
+
+/**
+ * The type Weighted random load balance(based on metadata).
+ *
+ * Weight rules:
+ * - Only supports non-negative weights (>= 0)
+ * - Weight can be configured in metadata with key "weight" as Number or String
+ * - Default weight is 1 if not specified
+ */
+@LoadLevel(name = LoadBalanceFactory.WEIGHTED_RANDOM_LOAD_BALANCE)
+public class WeightedRandomLoadBalance implements LoadBalance {
+
+ private static final LoadBalance RANDOM_LOAD_BALANCE =
+ EnhancedServiceLoader.load(LoadBalance.class, LoadBalanceFactory.RANDOM_LOAD_BALANCE);
+
+ private static final String WEIGHT_KEY = "weight";
+ private static final int DEFAULT_WEIGHT = 1;
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <T> T select(List<T> invokers, String xid) throws Exception {
+ // Check if all instances have no weight, if so downgrade to random load balancing
+ if (!hasAnyWeight(invokers)) {
+ return RANDOM_LOAD_BALANCE.select(invokers, xid);
+ }
+
+ // Calculate total weight
+ int totalWeight = calculateTotalWeight(invokers);
+
+ // If total weight is 0, downgrade to random load balancing
+ if (totalWeight <= 0) {
+ return RANDOM_LOAD_BALANCE.select(invokers, xid);
+ }
+
+ // Generate random numbers
+ int randomWeight = ThreadLocalRandom.current().nextInt(totalWeight);
+
+ // Select instances based on weights
+ int currentWeight = 0;
+ for (T invoker : invokers) {
+ if (invoker instanceof ServiceInstance) {
+ ServiceInstance instance = (ServiceInstance) invoker;
+ int weight = getWeight(instance);
+ currentWeight += weight;
+ if (randomWeight < currentWeight) {
+ return invoker;
+ }
+ }
+ }
+
+ return invokers.get(0);
+ }
+
+ /**
+ * Check if any instances contain valid weight information (weight > 0)
+ * @param invokers Instance List
+ * @return Returns true if any instance contains valid weight information
+ */
+ private <T> boolean hasAnyWeight(List<T> invokers) {
+ for (T invoker : invokers) {
+ if (invoker instanceof ServiceInstance) {
+ ServiceInstance instance = (ServiceInstance) invoker;
+ if (instance.getMetadata() != null && instance.getMetadata().containsKey(WEIGHT_KEY)) {
+ int weight = getWeight(instance);
+ if (weight > 0) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Calculate the total weight of all instances
+ * @param invokers Instance List
+ * @return Total weight
+ */
+ private <T> int calculateTotalWeight(List<T> invokers) {
+ int totalWeight = 0;
+ for (T invoker : invokers) {
+ if (invoker instanceof ServiceInstance) {
+ ServiceInstance instance = (ServiceInstance) invoker;
+ totalWeight += getWeight(instance);
+ }
+ }
+ return totalWeight;
+ }
+
+ /**
+ * Get the weight of the instance
+ * @param instance Instance
+ * @return Weight value, if not set returns the default weight of 1, negative weights are treated as 0
+ */
+ private int getWeight(ServiceInstance instance) {
+ if (instance.getMetadata() != null) {
+ Object weightObj = instance.getMetadata().get(WEIGHT_KEY);
+ if (weightObj != null) {
+ int weight = 0;
+ if (weightObj instanceof Number) {
+ weight = ((Number) weightObj).intValue();
+ } else if (weightObj instanceof String) {
+ try {
+ weight = Integer.parseInt((String) weightObj);
+ } catch (NumberFormatException e) {
+ return DEFAULT_WEIGHT;
+ }
+ }
+
+ // Only return non-negative weights
+ return Math.max(0, weight);
+ }
+ }
+ return DEFAULT_WEIGHT;
+ }
+}
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/XIDLoadBalance.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/XIDLoadBalance.java
index bc1d1c55cc..3567edc338 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/XIDLoadBalance.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/loadbalance/XIDLoadBalance.java
@@ -18,6 +18,7 @@ package org.apache.seata.discovery.loadbalance;
import org.apache.seata.common.loader.EnhancedServiceLoader;
import org.apache.seata.common.loader.LoadLevel;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -30,7 +31,6 @@ import static org.apache.seata.discovery.loadbalance.LoadBalanceFactory.XID_LOAD
/**
* The type xid load balance.
- *
*/
@LoadLevel(name = XID_LOAD_BALANCE)
public class XIDLoadBalance implements LoadBalance {
@@ -52,9 +52,9 @@ public class XIDLoadBalance implements LoadBalance {
String ip = serverAddress.substring(0, index);
InetSocketAddress xidInetSocketAddress = new InetSocketAddress(ip, port);
for (T invoker : invokers) {
- InetSocketAddress inetSocketAddress = (InetSocketAddress) invoker;
+ InetSocketAddress inetSocketAddress = ((ServiceInstance) invoker).getAddress();
if (Objects.equals(xidInetSocketAddress, inetSocketAddress)) {
- return (T) inetSocketAddress;
+ return invoker;
}
}
LOGGER.error("not found seata-server channel,xid: {}, try use random load balance", xid);
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/FileRegistryServiceImpl.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/FileRegistryServiceImpl.java
index 6b247d8da7..da3082563b 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/FileRegistryServiceImpl.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/FileRegistryServiceImpl.java
@@ -16,6 +16,7 @@
*/
package org.apache.seata.discovery.registry;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
import org.apache.seata.config.ConfigChangeListener;
@@ -29,7 +30,6 @@ import java.util.List;
/**
* The type File registry service.
- *
*/
public class FileRegistryServiceImpl implements RegistryService<ConfigChangeListener> {
@@ -57,10 +57,10 @@ public class FileRegistryServiceImpl implements RegistryService<ConfigChangeList
}
@Override
- public void register(InetSocketAddress address) throws Exception {}
+ public void register(ServiceInstance address) throws Exception {}
@Override
- public void unregister(InetSocketAddress address) throws Exception {}
+ public void unregister(ServiceInstance address) throws Exception {}
@Override
public void subscribe(String cluster, ConfigChangeListener listener) throws Exception {}
@@ -69,7 +69,10 @@ public class FileRegistryServiceImpl implements RegistryService<ConfigChangeList
public void unsubscribe(String cluster, ConfigChangeListener listener) throws Exception {}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public void close() throws Exception {}
+
+ @Override
+ public List<ServiceInstance> lookup(String key) throws Exception {
String clusterName = getServiceGroup(key);
if (clusterName == null) {
String missingDataId = PREFIX_SERVICE_ROOT + CONFIG_SPLIT_CHAR + PREFIX_SERVICE_MAPPING + key;
@@ -77,12 +80,13 @@ public class FileRegistryServiceImpl implements RegistryService<ConfigChangeList
}
String endpointStr = getGroupListFromConfig(clusterName);
String[] endpoints = endpointStr.split(ENDPOINT_SPLIT_CHAR);
- List<InetSocketAddress> inetSocketAddresses = new ArrayList<>();
+ List<ServiceInstance> serviceInstances = new ArrayList<>();
for (String endpoint : endpoints) {
String[] ipAndPort = NetUtil.splitIPPortStr(endpoint);
- inetSocketAddresses.add(new InetSocketAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1])));
+ serviceInstances.add(
+ new ServiceInstance(new InetSocketAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1]))));
}
- return inetSocketAddresses;
+ return serviceInstances;
}
private String getGroupListFromConfig(String clusterName) {
@@ -95,7 +99,4 @@ public class FileRegistryServiceImpl implements RegistryService<ConfigChangeList
}
return endpointStr;
}
-
- @Override
- public void close() throws Exception {}
}
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryHeartBeats.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryHeartBeats.java
index 69b380ad55..7798b2d383 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryHeartBeats.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryHeartBeats.java
@@ -28,7 +28,7 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
/**
- * @since 2021/6/13 5:09 pm
+ * Responsible for managing the heartbeat mechanism for registry centers.
*/
public class RegistryHeartBeats {
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryProvider.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryProvider.java
index 565ad0d9f5..c782754b55 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryProvider.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryProvider.java
@@ -20,6 +20,7 @@ package org.apache.seata.discovery.registry;
* the interface registry provider
*/
public interface RegistryProvider {
+
/**
* provide a registry implementation instance
* @return RegistryService
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryService.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryService.java
index b11a5a5940..81e5bb3245 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryService.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryService.java
@@ -16,11 +16,10 @@
*/
package org.apache.seata.discovery.registry;
-import org.apache.seata.common.metadata.Instance;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.config.ConfigurationFactory;
-import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
@@ -31,9 +30,9 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
- * The interface Registry service.
+ * Service registry interface for managing service registration and discovery.
*
- * @param <T> the type parameter
+ * @param <T> the listener type parameter
*/
public interface RegistryService<T> {
@@ -41,65 +40,45 @@ public interface RegistryService<T> {
* The constant PREFIX_SERVICE_MAPPING.
*/
String PREFIX_SERVICE_MAPPING = "vgroupMapping.";
+
/**
* The constant PREFIX_SERVICE_ROOT.
*/
String PREFIX_SERVICE_ROOT = "service";
+
/**
* The constant CONFIG_SPLIT_CHAR.
*/
String CONFIG_SPLIT_CHAR = ".";
- Set<String> SERVICE_GROUP_NAME = new HashSet<>();
-
/**
- * Service node health check
+ * Set of service group names.
*/
- Map<String, Map<String, List<InetSocketAddress>>> CURRENT_ADDRESS_MAP = new ConcurrentHashMap<>();
- /**
- * Register.
- *
- * @param address the address
- * @throws Exception the exception
- */
- @Deprecated
- void register(InetSocketAddress address) throws Exception;
+ Set<String> SERVICE_GROUP_NAME = new HashSet<>();
/**
- * Register.
- *
- * @param instance the address
- * @throws Exception the exception
+ * Current instance cache map for service node health check.
*/
- default void register(Instance instance) throws Exception {
- InetSocketAddress inetSocketAddress = new InetSocketAddress(
- instance.getTransaction().getHost(), instance.getTransaction().getPort());
- register(inetSocketAddress);
- }
+ Map<String, Map<String, List<ServiceInstance>>> CURRENT_INSTANCE_MAP = new ConcurrentHashMap<>();
/**
- * Unregister.
+ * Register a serviceInstance.
*
- * @param address the address
+ * @param address the serviceInstance to register
* @throws Exception the exception
*/
- @Deprecated
- void unregister(InetSocketAddress address) throws Exception;
+ void register(ServiceInstance address) throws Exception;
/**
- * Unregister.
+ * Unregister a serviceInstance.
*
- * @param instance the instance
+ * @param address the service instance to unregister
* @throws Exception the exception
*/
- default void unregister(Instance instance) throws Exception {
- InetSocketAddress inetSocketAddress = new InetSocketAddress(
- instance.getTransaction().getHost(), instance.getTransaction().getPort());
- unregister(inetSocketAddress);
- }
+ void unregister(ServiceInstance address) throws Exception;
/**
- * Subscribe.
+ * Subscribe to cluster changes.
*
* @param cluster the cluster
* @param listener the listener
@@ -108,7 +87,7 @@ public interface RegistryService<T> {
void subscribe(String cluster, T listener) throws Exception;
/**
- * Unsubscribe.
+ * Unsubscribe from cluster changes.
*
* @param cluster the cluster
* @param listener the listener
@@ -117,22 +96,22 @@ public interface RegistryService<T> {
void unsubscribe(String cluster, T listener) throws Exception;
/**
- * Lookup list.
+ * Look up serviceInstances by key.
*
* @param key the key
- * @return the list
+ * @return list of serviceInstances
* @throws Exception the exception
*/
- List<InetSocketAddress> lookup(String key) throws Exception;
+ List<ServiceInstance> lookup(String key) throws Exception;
/**
- * Close.
+ * Close the registry service.
* @throws Exception the exception
*/
void close() throws Exception;
/**
- * Get current service group name
+ * Get current service group name from configuration.
*
* @param key service group
* @return the service group name
@@ -145,57 +124,67 @@ public interface RegistryService<T> {
return ConfigurationFactory.getInstance().getConfig(key);
}
- default List<InetSocketAddress> aliveLookup(String transactionServiceGroup) {
- Map<String, List<InetSocketAddress>> clusterAddressMap =
- CURRENT_ADDRESS_MAP.computeIfAbsent(transactionServiceGroup, k -> new ConcurrentHashMap<>());
+ /**
+ * Look up alive serviceInstances for a transaction service group.
+ *
+ * @param transactionServiceGroup the transaction service group
+ * @return list of alive serviceInstances
+ */
+ default List<ServiceInstance> aliveLookup(String transactionServiceGroup) {
+ Map<String, List<ServiceInstance>> clusterInstanceMap =
+ CURRENT_INSTANCE_MAP.computeIfAbsent(transactionServiceGroup, key -> new ConcurrentHashMap<>());
String clusterName = getServiceGroup(transactionServiceGroup);
- List<InetSocketAddress> inetSocketAddresses = clusterAddressMap.get(clusterName);
- if (CollectionUtils.isNotEmpty(inetSocketAddresses)) {
- return inetSocketAddresses;
+ List<ServiceInstance> serviceInstances = clusterInstanceMap.get(clusterName);
+ if (CollectionUtils.isNotEmpty(serviceInstances)) {
+ return serviceInstances;
}
// fall back to addresses of any cluster
- return clusterAddressMap.values().stream()
+ return clusterInstanceMap.values().stream()
.filter(CollectionUtils::isNotEmpty)
.findAny()
.orElse(Collections.emptyList());
}
- default List<InetSocketAddress> refreshAliveLookup(
- String transactionServiceGroup, List<InetSocketAddress> aliveAddress) {
-
- Map<String, List<InetSocketAddress>> clusterAddressMap =
- CURRENT_ADDRESS_MAP.computeIfAbsent(transactionServiceGroup, key -> new ConcurrentHashMap<>());
+ /**
+ * Refresh alive serviceInstances for a transaction service group.
+ *
+ * @param transactionServiceGroup the transaction service group
+ * @param aliveInstances the alive instances to update
+ * @return the previous list of instances
+ */
+ default List<ServiceInstance> refreshAliveLookup(
+ String transactionServiceGroup, List<ServiceInstance> aliveInstances) {
+ Map<String, List<ServiceInstance>> clusterInstanceMap =
+ CURRENT_INSTANCE_MAP.computeIfAbsent(transactionServiceGroup, key -> new ConcurrentHashMap<>());
String clusterName = getServiceGroup(transactionServiceGroup);
- return clusterAddressMap.put(clusterName, aliveAddress);
+ return clusterInstanceMap.put(clusterName, aliveInstances);
}
/**
+ * Remove offline instances if necessary by intersecting old and new instances.
*
- * remove offline addresses if necessary.
- *
- * Intersection of the old and new addresses
- *
- * @param clusterName
- * @param newAddressed
+ * @param transactionGroupService the transaction group service
+ * @param clusterName the cluster name
+ * @param onlineInstances the online instances
*/
default void removeOfflineAddressesIfNecessary(
- String transactionGroupService, String clusterName, Collection<InetSocketAddress> newAddressed) {
+ String transactionGroupService, String clusterName, Collection<ServiceInstance> onlineInstances) {
- Map<String, List<InetSocketAddress>> clusterAddressMap =
- CURRENT_ADDRESS_MAP.computeIfAbsent(transactionGroupService, key -> new ConcurrentHashMap<>());
+ Map<String, List<ServiceInstance>> clusterInstanceMap =
+ CURRENT_INSTANCE_MAP.computeIfAbsent(transactionGroupService, key -> new ConcurrentHashMap<>());
- List<InetSocketAddress> currentAddresses = clusterAddressMap.getOrDefault(clusterName, Collections.emptyList());
+ List<ServiceInstance> currentInstances = clusterInstanceMap.getOrDefault(clusterName, Collections.emptyList());
- List<InetSocketAddress> inetSocketAddresses =
- currentAddresses.stream().filter(newAddressed::contains).collect(Collectors.toList());
+ List<ServiceInstance> serviceInstances =
+ currentInstances.stream().filter(onlineInstances::contains).collect(Collectors.toList());
// prevent empty update
- if (CollectionUtils.isNotEmpty(inetSocketAddresses)) {
- clusterAddressMap.put(clusterName, inetSocketAddresses);
+ if (CollectionUtils.isNotEmpty(serviceInstances)) {
+ clusterInstanceMap.put(clusterName, serviceInstances);
}
}
}
diff --git a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryType.java b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryType.java
index 4ae18a3048..0b4ac6e707 100644
--- a/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryType.java
+++ b/discovery/seata-discovery-core/src/main/java/org/apache/seata/discovery/registry/RegistryType.java
@@ -20,7 +20,6 @@ import org.apache.seata.common.exception.NotSupportYetException;
/**
* The enum Registry type.
- *
*/
public enum RegistryType {
/**
diff --git a/discovery/seata-discovery-core/src/main/resources/META-INF/services/org.apache.seata.discovery.loadbalance.LoadBalance b/discovery/seata-discovery-core/src/main/resources/META-INF/services/org.apache.seata.discovery.loadbalance.LoadBalance
index 49c1ff1da6..ceeacd214d 100644
--- a/discovery/seata-discovery-core/src/main/resources/META-INF/services/org.apache.seata.discovery.loadbalance.LoadBalance
+++ b/discovery/seata-discovery-core/src/main/resources/META-INF/services/org.apache.seata.discovery.loadbalance.LoadBalance
@@ -18,4 +18,5 @@ org.apache.seata.discovery.loadbalance.RoundRobinLoadBalance
org.apache.seata.discovery.loadbalance.RandomLoadBalance
org.apache.seata.discovery.loadbalance.ConsistentHashLoadBalance
org.apache.seata.discovery.loadbalance.LeastActiveLoadBalance
-org.apache.seata.discovery.loadbalance.XIDLoadBalance
\ No newline at end of file
+org.apache.seata.discovery.loadbalance.XIDLoadBalance
+org.apache.seata.discovery.loadbalance.WeightedRandomLoadBalance
\ No newline at end of file
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/config/ConfigurationFactoryTest.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/config/ConfigurationFactoryTest.java
deleted file mode 100644
index 8b205fdbbc..0000000000
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/config/ConfigurationFactoryTest.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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.seata.config;
-
-import org.apache.seata.discovery.loadbalance.ConsistentHashLoadBalance;
-import org.apache.seata.discovery.loadbalance.LoadBalanceFactory;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Test;
-
-class ConfigurationFactoryTest {
-
- @Test
- void getInstance() {
- Configuration configuration = ConfigurationFactory.getInstance();
- // check singleton
- Assertions.assertEquals(
- configuration.getClass().getName(),
- ConfigurationFactory.getInstance().getClass().getName());
- }
-
- @Test
- void getLoadBalance() {
- Configuration configuration = ConfigurationFactory.getInstance();
- String loadBalanceType = configuration.getConfig(LoadBalanceFactory.LOAD_BALANCE_TYPE);
- int virtualNode = configuration.getInt(ConsistentHashLoadBalance.LOAD_BALANCE_CONSISTENT_HASH_VIRTUAL_NODES);
- Assertions.assertEquals("XID", loadBalanceType);
- Assertions.assertEquals(10, virtualNode);
- }
-}
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactoryTest.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactoryTest.java
index 29d510a220..3d60ef782a 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactoryTest.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceFactoryTest.java
@@ -16,115 +16,47 @@
*/
package org.apache.seata.discovery.loadbalance;
-import org.apache.seata.discovery.registry.RegistryFactory;
-import org.apache.seata.discovery.registry.RegistryService;
-import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.Disabled;
-import org.junit.jupiter.params.ParameterizedTest;
-import org.junit.jupiter.params.provider.Arguments;
-import org.junit.jupiter.params.provider.MethodSource;
-
-import java.net.InetSocketAddress;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Stream;
-
-import static org.apache.seata.common.DefaultValues.DEFAULT_TX_GROUP;
+import org.apache.seata.config.Configuration;
+import org.apache.seata.config.ConfigurationFactory;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.when;
/**
* The type Load balance factory test.
- *
*/
public class LoadBalanceFactoryTest {
- private static final String XID = "XID";
+ private MockedStatic<ConfigurationFactory> mockedConfigurationFactory;
- /**
- * Test get registry.
- *
- * @param loadBalance the load balance
- * @throws Exception the exception
- */
- @ParameterizedTest
- @MethodSource("instanceProvider")
- @Disabled
- public void testGetRegistry(LoadBalance loadBalance) throws Exception {
- Assertions.assertNotNull(loadBalance);
- RegistryService registryService = RegistryFactory.getInstance();
- InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 8091);
- InetSocketAddress address2 = new InetSocketAddress("127.0.0.1", 8092);
- registryService.register(address1);
- registryService.register(address2);
- List<InetSocketAddress> addressList = registryService.lookup(DEFAULT_TX_GROUP);
- InetSocketAddress balanceAddress = loadBalance.select(addressList, XID);
- Assertions.assertNotNull(balanceAddress);
+ @BeforeEach
+ public void setUp() {
+ mockedConfigurationFactory = mockStatic(ConfigurationFactory.class);
}
- /**
- * Test get address.
- *
- * @param loadBalance the load balance
- * @throws Exception the exception
- */
- @ParameterizedTest
- @MethodSource("instanceProvider")
- @Disabled
- public void testUnRegistry(LoadBalance loadBalance) throws Exception {
- RegistryService registryService = RegistryFactory.getInstance();
- InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8091);
- registryService.unregister(address);
+ @AfterEach
+ public void tearDown() {
+ if (mockedConfigurationFactory != null) {
+ mockedConfigurationFactory.close();
+ }
}
- /**
- * Test subscribe.
- *
- * @param loadBalance the load balance
- * @throws Exception the exception
- */
- @ParameterizedTest
- @MethodSource("instanceProvider")
- @Disabled
- public void testSubscribe(LoadBalance loadBalance) throws Exception {
- Assertions.assertNotNull(loadBalance);
- RegistryService registryService = RegistryFactory.getInstance();
- InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 8091);
- InetSocketAddress address2 = new InetSocketAddress("127.0.0.1", 8092);
- registryService.register(address1);
- registryService.register(address2);
- List<InetSocketAddress> addressList = registryService.lookup(DEFAULT_TX_GROUP);
- InetSocketAddress balanceAddress = loadBalance.select(addressList, XID);
- Assertions.assertNotNull(balanceAddress);
- // wait trigger testUnRegistry
- TimeUnit.SECONDS.sleep(30);
- List<InetSocketAddress> addressList1 = registryService.lookup(DEFAULT_TX_GROUP);
- Assertions.assertEquals(1, addressList1.size());
- }
+ @Test
+ public void testGetInstance() {
+ Configuration mockConfig = mock(Configuration.class);
+ mockedConfigurationFactory.when(ConfigurationFactory::getInstance).thenReturn(mockConfig);
- /**
- * Test get address.
- *
- * @param loadBalance the load balance
- * @throws Exception the exception
- */
- @ParameterizedTest
- @MethodSource("instanceProvider")
- public void testGetAddress(LoadBalance loadBalance) throws Exception {
- Assertions.assertNotNull(loadBalance);
- InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8091);
- List<InetSocketAddress> addressList = new ArrayList<>();
- addressList.add(address);
- InetSocketAddress balanceAddress = loadBalance.select(addressList, XID);
- Assertions.assertEquals(address, balanceAddress);
- }
+ when(mockConfig.getConfig(eq("client.loadBalance.type"), anyString())).thenReturn("XID");
- /**
- * Instance provider object [ ] [ ].
- *
- * @return the object [ ] [ ]
- */
- static Stream<Arguments> instanceProvider() {
LoadBalance loadBalance = LoadBalanceFactory.getInstance();
- return Stream.of(Arguments.of(loadBalance));
+ assertInstanceOf(XIDLoadBalance.class, loadBalance);
}
}
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceTest.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceTest.java
index 8eac1190f0..5079fbe9c7 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceTest.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/loadbalance/LoadBalanceTest.java
@@ -16,8 +16,8 @@
*/
package org.apache.seata.discovery.loadbalance;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.rpc.RpcStatus;
-import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@@ -25,6 +25,7 @@ import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -32,9 +33,11 @@ import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Stream;
-/**
- * Created by guoyao on 2019/2/14.
- */
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
public class LoadBalanceTest {
private static final String XID = "XID";
@@ -42,155 +45,200 @@ public class LoadBalanceTest {
/**
* Test random load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testRandomLoadBalance_select(List<InetSocketAddress> addresses) {
+ @MethodSource("instanceProvider")
+ public void testRandomLoadBalance_select(List<ServiceInstance> instances) throws Exception {
int runs = 10000;
- Map<InetSocketAddress, AtomicLong> counter = getSelectedCounter(runs, addresses, new RandomLoadBalance());
- for (InetSocketAddress address : counter.keySet()) {
- Long count = counter.get(address).get();
- Assertions.assertTrue(count > 0, "selecte one time at last");
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, new RandomLoadBalance());
+ for (ServiceInstance instance : counter.keySet()) {
+ Long count = counter.get(instance).get();
+ assertTrue(count > 0, "selecte one time at last");
}
}
/**
- * Test round robin load balance select.
+ * Test round-robin load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testRoundRobinLoadBalance_select(List<InetSocketAddress> addresses) {
+ @MethodSource("instanceProvider")
+ public void testRoundRobinLoadBalance_select(List<ServiceInstance> instances) throws Exception {
int runs = 10000;
- Map<InetSocketAddress, AtomicLong> counter = getSelectedCounter(runs, addresses, new RoundRobinLoadBalance());
- for (InetSocketAddress address : counter.keySet()) {
- Long count = counter.get(address).get();
- Assertions.assertTrue(Math.abs(count - runs / (0f + addresses.size())) < 1f, "abs diff shoud < 1");
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, new RoundRobinLoadBalance());
+ for (ServiceInstance instance : counter.keySet()) {
+ Long count = counter.get(instance).get();
+ assertTrue(Math.abs(count - runs / (0f + instances.size())) < 1f, "abs diff shoud < 1");
}
}
/**
* Test xid load load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testXIDLoadBalance_select(List<InetSocketAddress> addresses) throws Exception {
+ @MethodSource("instanceProvider")
+ public void testXIDLoadBalance_select(List<ServiceInstance> instances) throws Exception {
XIDLoadBalance loadBalance = new XIDLoadBalance();
// ipv4
- InetSocketAddress inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8092:123456");
- Assertions.assertNotNull(inetSocketAddress);
+ ServiceInstance serviceInstance = loadBalance.select(instances, "127.0.0.1:8092:123456");
+ assertNotNull(serviceInstance);
// ipv6
- inetSocketAddress = loadBalance.select(addresses, "2000:0000:0000:0000:0001:2345:6789:abcd:8092:123456");
- Assertions.assertNotNull(inetSocketAddress);
+ serviceInstance = loadBalance.select(instances, "2000:0000:0000:0000:0001:2345:6789:abcd:8092:123456");
+ assertNotNull(serviceInstance);
// test not found tc channel
- inetSocketAddress = loadBalance.select(addresses, "127.0.0.1:8199:123456");
- Assertions.assertNotEquals(inetSocketAddress.getPort(), 8199);
+ serviceInstance = loadBalance.select(instances, "127.0.0.1:8199:123456");
+ assertNotEquals(serviceInstance.getAddress().getPort(), 8199);
}
/**
- * Test consistent hash load load balance select.
+ * Test consistent hash load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testConsistentHashLoadBalance_select(List<InetSocketAddress> addresses) {
+ @MethodSource("instanceProvider")
+ public void testConsistentHashLoadBalance_select(List<ServiceInstance> instances) throws Exception {
int runs = 10000;
int selected = 0;
ConsistentHashLoadBalance loadBalance = new ConsistentHashLoadBalance();
- Map<InetSocketAddress, AtomicLong> counter = getSelectedCounter(runs, addresses, loadBalance);
- for (InetSocketAddress address : counter.keySet()) {
- if (counter.get(address).get() > 0) {
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, loadBalance);
+ for (ServiceInstance instance : counter.keySet()) {
+ if (counter.get(instance).get() > 0) {
selected++;
}
}
- Assertions.assertEquals(1, selected, "selected must be equal to 1");
+ assertEquals(1, selected, "selected must be equal to 1");
}
/**
* Test cached consistent hash load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testCachedConsistentHashLoadBalance_select(List<InetSocketAddress> addresses) throws Exception {
+ @MethodSource("instanceProvider")
+ public void testCachedConsistentHashLoadBalance_select(List<ServiceInstance> instances) throws Exception {
ConsistentHashLoadBalance loadBalance = new ConsistentHashLoadBalance();
- List<InetSocketAddress> addresses1 = new ArrayList<>(addresses);
- loadBalance.select(addresses1, XID);
+ List<ServiceInstance> instances1 = new ArrayList<>(instances);
+ loadBalance.select(instances1, XID);
Object o1 = getConsistentHashSelectorByReflect(loadBalance);
- List<InetSocketAddress> addresses2 = new ArrayList<>(addresses);
- loadBalance.select(addresses2, XID);
+ List<ServiceInstance> instances2 = new ArrayList<>(instances);
+ loadBalance.select(instances2, XID);
Object o2 = getConsistentHashSelectorByReflect(loadBalance);
- Assertions.assertEquals(o1, o2);
+ assertEquals(o1, o2);
- List<InetSocketAddress> addresses3 = new ArrayList<>(addresses);
- addresses3.remove(ThreadLocalRandom.current().nextInt(addresses.size()));
- loadBalance.select(addresses3, XID);
+ List<ServiceInstance> instances3 = new ArrayList<>(instances);
+ instances3.remove(ThreadLocalRandom.current().nextInt(instances.size()));
+ loadBalance.select(instances3, XID);
Object o3 = getConsistentHashSelectorByReflect(loadBalance);
- Assertions.assertNotEquals(o1, o3);
+ assertNotEquals(o1, o3);
}
/**
* Test least active load balance select.
*
- * @param addresses the addresses
+ * @param instances the instances
*/
@ParameterizedTest
- @MethodSource("addressProvider")
- public void testLeastActiveLoadBalance_select(List<InetSocketAddress> addresses) throws Exception {
+ @MethodSource("instanceProvider")
+ public void testLeastActiveLoadBalance_select(List<ServiceInstance> instances) throws Exception {
int runs = 10000;
- int size = addresses.size();
+ int size = instances.size();
for (int i = 0; i < size - 1; i++) {
- RpcStatus.beginCount(addresses.get(i).toString());
+ RpcStatus.beginCount(instances.get(i).getAddress().toString());
}
- InetSocketAddress socketAddress = addresses.get(size - 1);
+ ServiceInstance targetInstance = instances.get(size - 1);
LoadBalance loadBalance = new LeastActiveLoadBalance();
for (int i = 0; i < runs; i++) {
- InetSocketAddress selectAddress = loadBalance.select(addresses, XID);
- Assertions.assertEquals(selectAddress, socketAddress);
+ ServiceInstance selectInstance = loadBalance.select(instances, XID);
+ assertEquals(selectInstance, targetInstance);
}
- RpcStatus.beginCount(socketAddress.toString());
- RpcStatus.beginCount(socketAddress.toString());
- Map<InetSocketAddress, AtomicLong> counter = getSelectedCounter(runs, addresses, loadBalance);
- for (InetSocketAddress address : counter.keySet()) {
- Long count = counter.get(address).get();
- if (address == socketAddress) {
- Assertions.assertEquals(count, 0);
+ RpcStatus.beginCount(targetInstance.getAddress().toString());
+ RpcStatus.beginCount(targetInstance.getAddress().toString());
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, loadBalance);
+ for (ServiceInstance instance : counter.keySet()) {
+ Long count = counter.get(instance).get();
+ if (instance == targetInstance) {
+ assertEquals(count, 0);
} else {
- Assertions.assertTrue(count > 0);
+ assertTrue(count > 0);
}
}
}
/**
- * Gets selected counter.
+ * Test weighted random load balance select with instances without weights.
+ * Should downgrade to random load balancing.
*
- * @param runs the runs
- * @param addresses the addresses
- * @param loadBalance the load balance
- * @return the selected counter
+ * @param instances the instances without weights
*/
- public Map<InetSocketAddress, AtomicLong> getSelectedCounter(
- int runs, List<InetSocketAddress> addresses, LoadBalance loadBalance) {
- Assertions.assertNotNull(loadBalance);
- Map<InetSocketAddress, AtomicLong> counter = new ConcurrentHashMap<>();
- for (InetSocketAddress address : addresses) {
- counter.put(address, new AtomicLong(0));
+ @ParameterizedTest
+ @MethodSource("instanceProvider")
+ public void testWeightedRandomLoadBalance_selectWithoutWeights(List<ServiceInstance> instances) throws Exception {
+ int runs = 10000;
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, new WeightedRandomLoadBalance());
+
+ // Verify all instances are selected roughly equally (random distribution)
+ for (ServiceInstance instance : counter.keySet()) {
+ Long count = counter.get(instance).get();
+ assertTrue(count > 0);
+
+ // In random distribution, each instance should be selected roughly 1/n times
+ double expectedCount = runs / (double) instances.size();
+ double actualCount = count;
+ double tolerance = expectedCount * 0.2; // 20% tolerance
+ assertTrue(Math.abs(actualCount - expectedCount) < tolerance);
}
- try {
- for (int i = 0; i < runs; i++) {
- InetSocketAddress selectAddress = loadBalance.select(addresses, XID);
- counter.get(selectAddress).incrementAndGet();
- }
- } catch (Exception e) {
- // do nothing
+ }
+
+ /**
+ * Test weighted random load balance select with weighted instances.
+ * Verifies that instances with higher weights are selected more frequently.
+ *
+ * @param instances the instances with weights configured
+ */
+ @ParameterizedTest
+ @MethodSource("weightedInstanceProvider")
+ public void testWeightedRandomLoadBalance_selectWithWeights(List<ServiceInstance> instances) throws Exception {
+ int runs = 10000;
+ Map<ServiceInstance, AtomicLong> counter = getSelectedCounter(runs, instances, new WeightedRandomLoadBalance());
+
+ // Verify all instances are selected at least once
+ for (ServiceInstance instance : counter.keySet()) {
+ Long count = counter.get(instance).get();
+ assertTrue(count > 0);
+ }
+
+ // Verify that instances with higher weights are selected more frequently
+ verifyWeightedDistribution(instances, counter);
+ }
+
+ /**
+ * Get the selection count for each ServiceInstance after running the load balancing algorithm multiple times.
+ *
+ * @param runs the number of times to perform selection
+ * @param instances the list of service instances to select from
+ * @param loadBalance the load balancing strategy to use
+ * @return a map where the key is the ServiceInstance and the value is the number of times it was selected
+ */
+ public Map<ServiceInstance, AtomicLong> getSelectedCounter(
+ int runs, List<ServiceInstance> instances, LoadBalance loadBalance) throws Exception {
+ assertNotNull(loadBalance);
+ Map<ServiceInstance, AtomicLong> counter = new ConcurrentHashMap<>();
+ for (ServiceInstance instance : instances) {
+ counter.put(instance, new AtomicLong(0));
+ }
+
+ for (int i = 0; i < runs; i++) {
+ ServiceInstance selectInstance = loadBalance.select(instances, XID);
+ counter.get(selectInstance).incrementAndGet();
}
+
return counter;
}
@@ -204,24 +252,111 @@ public class LoadBalanceTest {
Field selectorWrapperField = ConsistentHashLoadBalance.class.getDeclaredField("selectorWrapper");
selectorWrapperField.setAccessible(true);
Object selectWrapper = selectorWrapperField.get(loadBalance);
- Assertions.assertNotNull(selectWrapper);
+ assertNotNull(selectWrapper);
Field selectorField = selectWrapper.getClass().getDeclaredField("selector");
selectorField.setAccessible(true);
return selectorField.get(selectWrapper);
}
/**
- * Address provider object [ ] [ ].
+ * Provides a stream of service instance lists for parameterized tests.
*
- * @return Stream<List < InetSocketAddress>>
+ * @return Stream<List < ServiceInstance>> service instance lists
*/
- static Stream<List<InetSocketAddress>> addressProvider() {
+ static Stream<List<ServiceInstance>> instanceProvider() {
return Stream.of(Arrays.asList(
- new InetSocketAddress("127.0.0.1", 8091),
- new InetSocketAddress("127.0.0.1", 8092),
- new InetSocketAddress("127.0.0.1", 8093),
- new InetSocketAddress("127.0.0.1", 8094),
- new InetSocketAddress("127.0.0.1", 8095),
- new InetSocketAddress("2000:0000:0000:0000:0001:2345:6789:abcd", 8092)));
+ new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091)),
+ new ServiceInstance(new InetSocketAddress("127.0.0.1", 8092)),
+ new ServiceInstance(new InetSocketAddress("127.0.0.1", 8093)),
+ new ServiceInstance(new InetSocketAddress("127.0.0.1", 8094)),
+ new ServiceInstance(new InetSocketAddress("127.0.0.1", 8095)),
+ new ServiceInstance(new InetSocketAddress("2000:0000:0000:0000:0001:2345:6789:abcd", 8092))));
+ }
+
+ /**
+ * Provides a stream of weighted service instance lists for parameterized tests.
+ *
+ * @return Stream<List<ServiceInstance>> weighted service instance lists
+ */
+ static Stream<List<ServiceInstance>> weightedInstanceProvider() {
+ return Stream.of(Arrays.asList(
+ createWeightedInstance("127.0.0.1", 8091, 2),
+ createWeightedInstance("127.0.0.1", 8092, 3),
+ createWeightedInstance("127.0.0.1", 8093, 1),
+ createWeightedInstance("127.0.0.1", 8094, 4),
+ createWeightedInstance("127.0.0.1", 8095, 2)));
+ }
+
+ /**
+ * Verify that the selection distribution roughly matches the configured weights.
+ * Instances with higher weights should be selected more frequently.
+ *
+ * @param instances the list of service instances
+ * @param counter the selection count for each instance
+ */
+ private void verifyWeightedDistribution(List<ServiceInstance> instances, Map<ServiceInstance, AtomicLong> counter) {
+ // Calculate total weight and expected selection ratios
+ int totalWeight = 0;
+ Map<ServiceInstance, Integer> weights = new HashMap<>();
+
+ for (ServiceInstance instance : instances) {
+ int weight = getWeightFromInstance(instance);
+ weights.put(instance, weight);
+ totalWeight += weight;
+ }
+
+ if (totalWeight > 0) {
+ // Verify that instances with higher weights are selected more frequently
+ for (ServiceInstance instance : instances) {
+ int weight = weights.get(instance);
+ if (weight > 0) {
+ double expectedRatio = (double) weight / totalWeight;
+ double actualRatio = (double) counter.get(instance).get()
+ / counter.values().stream()
+ .mapToLong(AtomicLong::get)
+ .sum();
+
+ // Allow 30% tolerance for random distribution
+ double tolerance = expectedRatio * 0.3;
+ assertTrue(Math.abs(actualRatio - expectedRatio) < tolerance);
+ }
+ }
+ }
+ }
+
+ /**
+ * Extract weight from ServiceInstance metadata.
+ *
+ * @param instance the service instance
+ * @return the weight value, default is 1 if not configured
+ */
+ private int getWeightFromInstance(ServiceInstance instance) {
+ if (instance.getMetadata() != null && instance.getMetadata().containsKey("weight")) {
+ Object weightObj = instance.getMetadata().get("weight");
+ if (weightObj instanceof Number) {
+ return Math.max(0, ((Number) weightObj).intValue());
+ } else if (weightObj instanceof String) {
+ try {
+ return Math.max(0, Integer.parseInt((String) weightObj));
+ } catch (NumberFormatException e) {
+ return 1;
+ }
+ }
+ }
+ return 1;
+ }
+
+ /**
+ * Helper method to create a weighted service instance.
+ *
+ * @param host the host
+ * @param port the port
+ * @param weight the weight value
+ * @return ServiceInstance with weight configured in metadata
+ */
+ private static ServiceInstance createWeightedInstance(String host, int port, int weight) {
+ Map<String, Object> metadata = new HashMap<>();
+ metadata.put("weight", weight);
+ return new ServiceInstance(new InetSocketAddress(host, port), metadata);
}
}
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryProviderTest.java
similarity index 68%
copy from discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java
copy to discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryProviderTest.java
index c9b769b88e..f196c4fcf2 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryProviderTest.java
@@ -16,15 +16,17 @@
*/
package org.apache.seata.discovery.registry;
-import org.apache.seata.common.loader.LoadLevel;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-/**
- * the mock nacos RegistryProvider
- */
-@LoadLevel(name = "Nacos", order = 1)
-public class MockNacosRegistryProvider implements RegistryProvider {
- @Override
- public RegistryService provide() {
- return new MockNacosRegistryService();
+class FileRegistryProviderTest {
+
+ @Test
+ void testProvide() {
+ RegistryProvider provider = new FileRegistryProvider();
+ RegistryService<?> service = provider.provide();
+
+ Assertions.assertNotNull(service);
+ Assertions.assertInstanceOf(FileRegistryServiceImpl.class, service);
}
}
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryServiceImplTest.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryServiceImplTest.java
new file mode 100644
index 0000000000..ebdc5db486
--- /dev/null
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/FileRegistryServiceImplTest.java
@@ -0,0 +1,161 @@
+/*
+ * 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.seata.discovery.registry;
+
+import org.apache.seata.common.metadata.ServiceInstance;
+import org.apache.seata.config.ConfigChangeListener;
+import org.apache.seata.config.Configuration;
+import org.apache.seata.config.ConfigurationFactory;
+import org.apache.seata.config.exception.ConfigNotFoundException;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.lang.reflect.Field;
+import java.net.InetSocketAddress;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.when;
+
+class FileRegistryServiceImplTest {
+
+ private static final String TEST_GROUP = "testGroup";
+ private static final String TEST_CLUSTER = "default_tx_group";
+
+ private final ServiceInstance serviceInstance1 = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8080));
+ private final ServiceInstance serviceInstance2 = new ServiceInstance(new InetSocketAddress("127.0.0.2", 8080));
+
+ private static FileRegistryServiceImpl fileRegistryService;
+
+ @BeforeAll
+ public static void setUp() {
+ System.setProperty("service.vgroupMapping.testGroup", TEST_GROUP);
+ fileRegistryService = FileRegistryServiceImpl.getInstance();
+ }
+
+ @Test
+ public void testEmptyMethod() throws Exception {
+ fileRegistryService.register(serviceInstance1);
+ fileRegistryService.unregister(serviceInstance1);
+
+ ConfigChangeListener configChangeListener = new ConfigChangeListener() {
+ @Override
+ public ExecutorService getExecutor() {
+ return null;
+ }
+
+ @Override
+ public void receiveConfigInfo(String configInfo) {}
+ };
+
+ fileRegistryService.subscribe(TEST_CLUSTER, configChangeListener);
+ fileRegistryService.unsubscribe(TEST_CLUSTER, configChangeListener);
+
+ fileRegistryService.close();
+ }
+
+ /**
+ * Tests the getServiceGroup method to ensure it retrieves the correct service group name
+ */
+ @Test
+ public void testGetServiceGroup() {
+ String result = fileRegistryService.getServiceGroup(TEST_GROUP);
+ assertEquals(TEST_GROUP, result);
+ }
+
+ /**
+ * Tests the aliveLookup and refreshAliveLookup methods.
+ */
+ @Test
+ public void testAliveLookupAndRefreshAliveLookup() {
+ RegistryService.CURRENT_INSTANCE_MAP.clear();
+ List<ServiceInstance> serviceInstances = Collections.singletonList(serviceInstance1);
+
+ // Test empty list
+ List<ServiceInstance> result = fileRegistryService.aliveLookup(TEST_GROUP);
+ assertTrue(result.isEmpty());
+
+ // Test data is available
+ fileRegistryService.refreshAliveLookup(TEST_GROUP, serviceInstances);
+ result = fileRegistryService.aliveLookup(TEST_GROUP);
+ assertEquals(serviceInstances, result);
+ }
+
+ /**
+ * Tests the removeOfflineAddressesIfNecessary method when there is no intersection
+ */
+ @Test
+ public void testRemoveOfflineAddressesIfNecessaryWithNoIntersection() {
+ List<ServiceInstance> currentInstances = Collections.singletonList(serviceInstance1);
+ Collection<ServiceInstance> newInstances = Collections.singletonList(serviceInstance2);
+
+ fileRegistryService.refreshAliveLookup(TEST_GROUP, currentInstances);
+ fileRegistryService.removeOfflineAddressesIfNecessary(
+ TEST_GROUP, fileRegistryService.getServiceGroup(TEST_GROUP), newInstances);
+
+ List<ServiceInstance> result = fileRegistryService.aliveLookup(TEST_GROUP);
+ assertFalse(result.isEmpty());
+ assertEquals(currentInstances, result);
+ }
+
+ /**
+ * Tests the removeOfflineAddressesIfNecessary method when there is an intersection
+ */
+ @Test
+ public void testRemoveOfflineAddressesIfNecessaryWithIntersection() {
+ List<ServiceInstance> currentInstances = Arrays.asList(serviceInstance1, serviceInstance2);
+ Collection<ServiceInstance> newInstances = Collections.singletonList(serviceInstance1);
+
+ fileRegistryService.refreshAliveLookup(TEST_GROUP, currentInstances);
+ fileRegistryService.removeOfflineAddressesIfNecessary(
+ TEST_GROUP, fileRegistryService.getServiceGroup(TEST_GROUP), newInstances);
+
+ List<ServiceInstance> result = fileRegistryService.aliveLookup(TEST_GROUP);
+ assertFalse(result.isEmpty());
+ assertEquals(new HashSet<>(newInstances), new HashSet<>(result));
+ }
+
+ @Test
+ public void testLookup() throws Exception {
+ List<ServiceInstance> lookup = fileRegistryService.lookup(TEST_CLUSTER);
+ assertEquals(serviceInstance1, lookup.get(0));
+
+ // Set the getServiceGroup() to return null by reflection
+ Configuration mockConfig = Mockito.mock(Configuration.class);
+ when(mockConfig.getConfig("service.vgroupMapping.default_tx_group")).thenReturn(null);
+ Field configField = ConfigurationFactory.class.getDeclaredField("instance");
+ configField.setAccessible(true);
+ Object originalConfigInstance = configField.get(null);
+ configField.set(null, mockConfig);
+
+ try {
+ assertThrows(ConfigNotFoundException.class, () -> fileRegistryService.lookup(TEST_CLUSTER));
+ } finally {
+ // reset ConfigurationFactory.instance
+ configField.set(null, originalConfigInstance);
+ }
+ }
+}
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MultiRegistryFactoryTest.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MultiRegistryFactoryTest.java
index 3e82208ca9..c39c996bb0 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MultiRegistryFactoryTest.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MultiRegistryFactoryTest.java
@@ -23,6 +23,7 @@ import ch.qos.logback.core.read.ListAppender;
import org.apache.seata.common.ConfigurationKeys;
import org.apache.seata.common.Constants;
import org.apache.seata.common.exception.NotSupportYetException;
+import org.apache.seata.discovery.registry.mock.MockNacosRegistryService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryProvider.java
similarity index 86%
rename from discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java
rename to discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryProvider.java
index c9b769b88e..c1bed823f1 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryProvider.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryProvider.java
@@ -14,9 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.seata.discovery.registry;
+package org.apache.seata.discovery.registry.mock;
import org.apache.seata.common.loader.LoadLevel;
+import org.apache.seata.discovery.registry.RegistryProvider;
+import org.apache.seata.discovery.registry.RegistryService;
/**
* the mock nacos RegistryProvider
diff --git a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryService.java b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryService.java
similarity index 77%
rename from discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryService.java
rename to discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryService.java
index 03aaabf1dc..c5c4efdff3 100644
--- a/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/MockNacosRegistryService.java
+++ b/discovery/seata-discovery-core/src/test/java/org/apache/seata/discovery/registry/mock/MockNacosRegistryService.java
@@ -14,9 +14,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.seata.discovery.registry;
+package org.apache.seata.discovery.registry.mock;
+
+import org.apache.seata.common.metadata.ServiceInstance;
+import org.apache.seata.discovery.registry.RegistryService;
-import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
@@ -26,10 +28,10 @@ import java.util.List;
public class MockNacosRegistryService implements RegistryService<Object> {
@Override
- public void register(InetSocketAddress address) throws Exception {}
+ public void register(ServiceInstance address) throws Exception {}
@Override
- public void unregister(InetSocketAddress address) throws Exception {}
+ public void unregister(ServiceInstance address) throws Exception {}
@Override
public void subscribe(String cluster, Object listener) throws Exception {}
@@ -38,7 +40,7 @@ public class MockNacosRegistryService implements RegistryService<Object> {
public void unsubscribe(String cluster, Object listener) throws Exception {}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
return new ArrayList<>();
}
diff --git a/discovery/seata-discovery-core/src/test/resources/META-INF/services/org.apache.seata.discovery.registry.RegistryProvider b/discovery/seata-discovery-core/src/test/resources/META-INF/services/org.apache.seata.discovery.registry.RegistryProvider
index f3809a6d55..ef894d58de 100644
--- a/discovery/seata-discovery-core/src/test/resources/META-INF/services/org.apache.seata.discovery.registry.RegistryProvider
+++ b/discovery/seata-discovery-core/src/test/resources/META-INF/services/org.apache.seata.discovery.registry.RegistryProvider
@@ -14,4 +14,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-org.apache.seata.discovery.registry.MockNacosRegistryProvider
\ No newline at end of file
+org.apache.seata.discovery.registry.mock.MockNacosRegistryProvider
\ No newline at end of file
diff --git a/discovery/seata-discovery-core/src/test/resources/file.conf b/discovery/seata-discovery-core/src/test/resources/file.conf
index c0f8fd3368..4ea9c29f35 100644
--- a/discovery/seata-discovery-core/src/test/resources/file.conf
+++ b/discovery/seata-discovery-core/src/test/resources/file.conf
@@ -22,3 +22,12 @@ client {
virtualNodes = 10
}
}
+
+service {
+ # transaction service group mapping
+ vgroupMapping.default_tx_group = "default"
+ # only support when registry.type=file, please don't set multiple addresses
+ default.grouplist = "127.0.0.1:8080"
+ # disable seata
+ disableGlobalTransaction = false
+}
diff --git a/discovery/seata-discovery-core/src/test/resources/registry.conf b/discovery/seata-discovery-core/src/test/resources/registry.conf
index 8b8a0f5b88..5ad014bf55 100644
--- a/discovery/seata-discovery-core/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-core/src/test/resources/registry.conf
@@ -19,44 +19,6 @@ registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "file"
- nacos {
- application = "seata-server"
- serverAddr = "localhost"
- namespace = ""
- cluster = "default"
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- application = "default"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- consul {
- cluster = "default"
- serverAddr = "127.0.0.1:8500"
- }
- etcd3 {
- cluster = "default"
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- application = "default"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- cluster = "default"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
file {
name = "file.conf"
}
@@ -66,27 +28,6 @@ config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
- nacos {
- serverAddr = "localhost"
- namespace = ""
- group = "SEATA_GROUP"
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- }
- apollo {
- appId = "seata-server"
- apolloMeta = "http://192.168.1.204:8801"
- namespace = "application"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
file {
name = "file.conf"
}
diff --git a/discovery/seata-discovery-custom/src/test/java/org/apache/seata/discovery/registry/custom/CustomRegistryServiceForTest.java b/discovery/seata-discovery-custom/src/test/java/org/apache/seata/discovery/registry/custom/CustomRegistryServiceForTest.java
index 19d426e273..fa830dce14 100644
--- a/discovery/seata-discovery-custom/src/test/java/org/apache/seata/discovery/registry/custom/CustomRegistryServiceForTest.java
+++ b/discovery/seata-discovery-custom/src/test/java/org/apache/seata/discovery/registry/custom/CustomRegistryServiceForTest.java
@@ -16,35 +16,35 @@
*/
package org.apache.seata.discovery.registry.custom;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.config.ConfigChangeListener;
import org.apache.seata.discovery.registry.RegistryService;
-import java.net.InetSocketAddress;
import java.util.List;
public class CustomRegistryServiceForTest implements RegistryService<ConfigChangeListener> {
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) {
throw new UnsupportedOperationException();
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) {
throw new UnsupportedOperationException();
}
@Override
- public void subscribe(String cluster, ConfigChangeListener listener) throws Exception {
+ public void subscribe(String cluster, ConfigChangeListener listener) {
throw new UnsupportedOperationException();
}
@Override
- public void unsubscribe(String cluster, ConfigChangeListener listener) throws Exception {
+ public void unsubscribe(String cluster, ConfigChangeListener listener) {
throw new UnsupportedOperationException();
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) {
throw new UnsupportedOperationException();
}
diff --git a/discovery/seata-discovery-etcd3/src/main/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java b/discovery/seata-discovery-etcd3/src/main/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java
index 710dd2dbb4..045028ff8e 100644
--- a/discovery/seata-discovery-etcd3/src/main/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java
+++ b/discovery/seata-discovery-etcd3/src/main/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImpl.java
@@ -28,6 +28,7 @@ import io.etcd.jetcd.options.PutOption;
import io.etcd.jetcd.options.WatchOption;
import io.etcd.jetcd.watch.WatchResponse;
import org.apache.seata.common.exception.ShouldNeverHappenException;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -90,7 +91,7 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
private static volatile EtcdRegistryServiceImpl instance;
private static volatile Client client;
- private ConcurrentMap<String, Pair<Long /*revision*/, List<InetSocketAddress>>> clusterAddressMap;
+ private ConcurrentMap<String, Pair<Long /*revision*/, List<ServiceInstance>>> clusterAddressMap;
private ConcurrentMap<String, Set<Watch.Listener>> listenerMap;
private ConcurrentMap<String, EtcdWatcher> watcherMap;
private static long leaseId = 0;
@@ -131,7 +132,8 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
doRegister(address);
RegistryHeartBeats.addHeartBeat(REGISTRY_TYPE, address, this::doRegister);
@@ -151,7 +153,8 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
doUnregister(address);
}
@@ -167,14 +170,14 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
}
@Override
- public void subscribe(String cluster, Watch.Listener listener) throws Exception {
+ public void subscribe(String cluster, Watch.Listener listener) {
listenerMap.computeIfAbsent(cluster, key -> new HashSet<>()).add(listener);
EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(cluster, listener));
executorService.submit(watcher);
}
@Override
- public void unsubscribe(String cluster, Watch.Listener listener) throws Exception {
+ public void unsubscribe(String cluster, Watch.Listener listener) {
Set<Watch.Listener> subscribeSet = listenerMap.get(cluster);
if (subscribeSet != null) {
Set<Watch.Listener> newSubscribeSet = subscribeSet.stream()
@@ -187,7 +190,7 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
transactionServiceGroup = key;
final String cluster = getServiceGroup(key);
if (cluster == null) {
@@ -197,7 +200,7 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
return lookupByCluster(cluster);
}
- private List<InetSocketAddress> lookupByCluster(String cluster) throws Exception {
+ private List<ServiceInstance> lookupByCluster(String cluster) throws Exception {
if (!listenerMap.containsKey(cluster)) {
// 1.refresh
refreshCluster(cluster);
@@ -220,7 +223,7 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
public void onCompleted() {}
});
}
- Pair<Long, List<InetSocketAddress>> pair = clusterAddressMap.get(cluster);
+ Pair<Long, List<ServiceInstance>> pair = clusterAddressMap.get(cluster);
return Objects.isNull(pair) ? Collections.emptyList() : pair.getValue();
}
@@ -275,13 +278,13 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
.get(buildRegistryKeyPrefix(cluster), getOption)
.get();
// 2.add to list
- List<InetSocketAddress> instanceList = getResponse.getKvs().stream()
+ List<ServiceInstance> instanceList = ServiceInstance.convertToServiceInstanceSet(getResponse.getKvs().stream()
.map(keyValue -> {
String[] instanceInfo =
NetUtil.splitIPPortStr(keyValue.getValue().toString(UTF_8));
return new InetSocketAddress(instanceInfo[0], Integer.parseInt(instanceInfo[1]));
})
- .collect(Collectors.toList());
+ .collect(Collectors.toList()));
clusterAddressMap.put(cluster, new Pair<>(getResponse.getHeader().getRevision(), instanceList));
removeOfflineAddressesIfNecessary(transactionServiceGroup, cluster, instanceList);
@@ -436,7 +439,7 @@ public class EtcdRegistryServiceImpl implements RegistryService<Watch.Listener>
Watch watchClient = getClient().getWatchClient();
WatchOption.Builder watchOptionBuilder =
WatchOption.newBuilder().withPrefix(buildRegistryKeyPrefix(cluster));
- Pair<Long /*revision*/, List<InetSocketAddress>> addressPair = clusterAddressMap.get(cluster);
+ Pair<Long /*revision*/, List<ServiceInstance>> addressPair = clusterAddressMap.get(cluster);
if (Objects.nonNull(addressPair)) {
// Maybe addressPair isn't newest now, but it's ok
watchOptionBuilder.withRevision(addressPair.getKey());
diff --git a/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplMockTest.java b/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplMockTest.java
index 93b3cf20c1..cf53f96f13 100644
--- a/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplMockTest.java
+++ b/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplMockTest.java
@@ -31,6 +31,7 @@ import io.etcd.jetcd.lease.LeaseTimeToLiveResponse;
import io.etcd.jetcd.options.GetOption;
import io.etcd.jetcd.options.PutOption;
import io.etcd.jetcd.options.WatchOption;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
import org.apache.seata.config.exception.ConfigNotFoundException;
@@ -162,7 +163,7 @@ public class EtcdRegistryServiceImplMockTest {
.thenReturn(CompletableFuture.completedFuture(new LeaseKeepAliveResponse(leaseKeepAliveResponse)));
// Act
- registryService.register(address);
+ registryService.register(new ServiceInstance(address));
// verify the method to register the new service is called
verify(mockKVClient, times(1)).put(any(), any(), any(PutOption.class));
@@ -180,7 +181,7 @@ public class EtcdRegistryServiceImplMockTest {
when(mockKVClient.delete(any())).thenReturn(CompletableFuture.completedFuture(null));
// Act
- registryService.unregister(address);
+ registryService.unregister(new ServiceInstance(address));
// Verify
verify(mockKVClient, times(1)).delete(any());
@@ -199,9 +200,10 @@ public class EtcdRegistryServiceImplMockTest {
mockConfig.when(ConfigurationFactory::getInstance).thenReturn(configuration);
when(configuration.getConfig("service.vgroupMapping.default_tx_group"))
.thenReturn(CLUSTER_NAME);
- List<InetSocketAddress> lookup = registryService.lookup(DEFAULT_TX_GROUP);
+ List<ServiceInstance> lookup = registryService.lookup(DEFAULT_TX_GROUP);
List<String> lookupServices = lookup.stream()
- .map(address -> address.getHostString() + ":" + address.getPort())
+ .map(instance -> instance.getAddress().getAddress().getHostAddress() + ":"
+ + instance.getAddress().getPort())
.collect(Collectors.toList());
// assert
@@ -217,7 +219,7 @@ public class EtcdRegistryServiceImplMockTest {
@Order(4)
@Test
- public void testSubscribe() throws Exception {
+ public void testSubscribe() {
Watch.Listener mockListener = mock(Watch.Listener.class);
registryService.subscribe(CLUSTER_NAME, mockListener);
diff --git a/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplTest.java b/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplTest.java
index bfa9159821..37490b1a04 100644
--- a/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplTest.java
+++ b/discovery/seata-discovery-etcd3/src/test/java/org/apache/seata/discovery/registry/etcd3/EtcdRegistryServiceImplTest.java
@@ -23,6 +23,7 @@ import io.etcd.jetcd.launcher.junit4.EtcdClusterResource;
import io.etcd.jetcd.options.DeleteOption;
import io.etcd.jetcd.options.GetOption;
import io.etcd.jetcd.watch.WatchResponse;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.discovery.registry.RegistryService;
import org.junit.Rule;
import org.junit.jupiter.api.AfterAll;
@@ -68,7 +69,7 @@ public class EtcdRegistryServiceImplTest {
RegistryService registryService = new EtcdRegistryProvider().provide();
InetSocketAddress inetSocketAddress = new InetSocketAddress(HOST, PORT);
// 1.register
- registryService.register(inetSocketAddress);
+ registryService.register(new ServiceInstance(inetSocketAddress));
// 2.get instance information
GetOption getOption =
GetOption.newBuilder().withPrefix(buildRegistryKeyPrefix()).build();
@@ -84,9 +85,9 @@ public class EtcdRegistryServiceImplTest {
@Test
public void testUnregister() throws Exception {
RegistryService registryService = new EtcdRegistryProvider().provide();
- InetSocketAddress inetSocketAddress = new InetSocketAddress(HOST, PORT);
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress(HOST, PORT));
// 1.register
- registryService.register(inetSocketAddress);
+ registryService.register(serviceInstance);
// 2.get instance information
GetOption getOption =
GetOption.newBuilder().withPrefix(buildRegistryKeyPrefix()).build();
@@ -98,7 +99,7 @@ public class EtcdRegistryServiceImplTest {
.count();
assertThat(count).isEqualTo(1);
// 3.unregister
- registryService.unregister(inetSocketAddress);
+ registryService.unregister(serviceInstance);
// 4.again get instance information
getOption = GetOption.newBuilder().withPrefix(buildRegistryKeyPrefix()).build();
count = client.getKVClient().get(buildRegistryKeyPrefix(), getOption).get().getKvs().stream()
@@ -115,7 +116,7 @@ public class EtcdRegistryServiceImplTest {
RegistryService registryService = new EtcdRegistryProvider().provide();
InetSocketAddress inetSocketAddress = new InetSocketAddress(HOST, PORT);
// 1.register
- registryService.register(inetSocketAddress);
+ registryService.register(new ServiceInstance(inetSocketAddress));
// 2.subscribe
EtcdListener etcdListener = new EtcdListener();
registryService.subscribe(CLUSTER_NAME, etcdListener);
@@ -131,7 +132,7 @@ public class EtcdRegistryServiceImplTest {
RegistryService registryService = new EtcdRegistryProvider().provide();
InetSocketAddress inetSocketAddress = new InetSocketAddress(HOST, PORT);
// 1.register
- registryService.register(inetSocketAddress);
+ registryService.register(new ServiceInstance(inetSocketAddress));
// 2.subscribe
EtcdListener etcdListener = new EtcdListener();
registryService.subscribe(CLUSTER_NAME, etcdListener);
@@ -156,10 +157,10 @@ public class EtcdRegistryServiceImplTest {
RegistryService registryService = new EtcdRegistryProvider().provide();
InetSocketAddress inetSocketAddress = new InetSocketAddress(HOST, PORT);
// 1.register
- registryService.register(inetSocketAddress);
+ registryService.register(new ServiceInstance(inetSocketAddress));
// 2.lookup
- List<InetSocketAddress> inetSocketAddresses = registryService.lookup(DEFAULT_TX_GROUP);
- assertThat(inetSocketAddresses).size().isEqualTo(1);
+ List<ServiceInstance> serviceInstances = registryService.lookup(DEFAULT_TX_GROUP);
+ assertThat(serviceInstances).size().isEqualTo(1);
}
/**
diff --git a/discovery/seata-discovery-eureka/src/main/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImpl.java b/discovery/seata-discovery-eureka/src/main/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImpl.java
index 7cb2c79706..82ff23bb27 100644
--- a/discovery/seata-discovery-eureka/src/main/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImpl.java
+++ b/discovery/seata-discovery-eureka/src/main/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImpl.java
@@ -27,6 +27,7 @@ import com.netflix.discovery.EurekaEventListener;
import com.netflix.discovery.shared.Application;
import org.apache.seata.common.exception.EurekaRegistryException;
import org.apache.seata.common.lock.ResourceLock;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -69,7 +70,7 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
private static final Configuration FILE_CONFIG = ConfigurationFactory.CURRENT_FILE_INSTANCE;
private static final ConcurrentMap<String, List<EurekaEventListener>> LISTENER_SERVICE_MAP =
new ConcurrentHashMap<>();
- private static final ConcurrentMap<String, List<InetSocketAddress>> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<String, List<ServiceInstance>> CLUSTER_INSTANCE_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, ResourceLock> CLUSTER_LOCK = new ConcurrentHashMap<>();
private static volatile ApplicationInfoManager applicationInfoManager;
@@ -94,7 +95,8 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
instanceConfig.setIpAddress(address.getAddress().getHostAddress());
instanceConfig.setPort(address.getPort());
@@ -105,7 +107,7 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) {
if (eurekaClient == null) {
return;
}
@@ -113,13 +115,13 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
}
@Override
- public void subscribe(String cluster, EurekaEventListener listener) throws Exception {
+ public void subscribe(String cluster, EurekaEventListener listener) {
LISTENER_SERVICE_MAP.computeIfAbsent(cluster, key -> new ArrayList<>()).add(listener);
getEurekaClient(false).registerEventListener(listener);
}
@Override
- public void unsubscribe(String cluster, EurekaEventListener listener) throws Exception {
+ public void unsubscribe(String cluster, EurekaEventListener listener) {
List<EurekaEventListener> subscribeList = LISTENER_SERVICE_MAP.get(cluster);
if (subscribeList != null) {
List<EurekaEventListener> newSubscribeList = subscribeList.stream()
@@ -131,7 +133,7 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) {
transactionServiceGroup = key;
String clusterName = getServiceGroup(key);
if (clusterName == null) {
@@ -150,7 +152,7 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
}
}
}
- return CLUSTER_ADDRESS_MAP.get(clusterUpperName);
+ return CLUSTER_INSTANCE_MAP.get(clusterUpperName);
}
@Override
@@ -166,16 +168,17 @@ public class EurekaRegistryServiceImpl implements RegistryService<EurekaEventLis
if (application == null || CollectionUtils.isEmpty(application.getInstances())) {
LOGGER.info("refresh cluster success,but cluster empty! cluster name:{}", clusterName);
} else {
- List<InetSocketAddress> newAddressList = application.getInstances().stream()
- .filter(instance -> InstanceInfo.InstanceStatus.UP.equals(instance.getStatus())
- && instance.getIPAddr() != null
- && instance.getPort() > 0
- && instance.getPort() < 0xFFFF)
- .map(instance -> new InetSocketAddress(instance.getIPAddr(), instance.getPort()))
- .collect(Collectors.toList());
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ List<ServiceInstance> onlineInstanceList =
+ ServiceInstance.convertToServiceInstanceSet(application.getInstances().stream()
+ .filter(instance -> InstanceInfo.InstanceStatus.UP.equals(instance.getStatus())
+ && instance.getIPAddr() != null
+ && instance.getPort() > 0
+ && instance.getPort() < 0xFFFF)
+ .map(instance -> new InetSocketAddress(instance.getIPAddr(), instance.getPort()))
+ .collect(Collectors.toList()));
+ CLUSTER_INSTANCE_MAP.put(clusterName, onlineInstanceList);
- removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newAddressList);
+ removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, onlineInstanceList);
}
}
diff --git a/discovery/seata-discovery-eureka/src/test/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImplTest.java b/discovery/seata-discovery-eureka/src/test/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImplTest.java
index 0e0e78c55a..77b1d68f24 100644
--- a/discovery/seata-discovery-eureka/src/test/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImplTest.java
+++ b/discovery/seata-discovery-eureka/src/test/java/org/apache/seata/discovery/registry/eureka/EurekaRegistryServiceImplTest.java
@@ -21,6 +21,7 @@ import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaEventListener;
import com.netflix.discovery.shared.Application;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
import org.apache.seata.config.exception.ConfigNotFoundException;
@@ -79,7 +80,7 @@ public class EurekaRegistryServiceImplTest {
setStaticField(EurekaRegistryServiceImpl.class, "eurekaClient", null);
setStaticField(EurekaRegistryServiceImpl.class, "instanceConfig", null);
clearStaticMap(EurekaRegistryServiceImpl.class, "LISTENER_SERVICE_MAP");
- clearStaticMap(EurekaRegistryServiceImpl.class, "CLUSTER_ADDRESS_MAP");
+ clearStaticMap(EurekaRegistryServiceImpl.class, "CLUSTER_INSTANCE_MAP");
clearStaticMap(EurekaRegistryServiceImpl.class, "CLUSTER_LOCK");
}
@@ -93,7 +94,7 @@ public class EurekaRegistryServiceImplTest {
@Test
public void testRegister() throws Exception {
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8091);
- registryService.register(address);
+ registryService.register(new ServiceInstance(address));
CustomEurekaInstanceConfig instanceConfig = getInstanceConfig();
Assertions.assertEquals("127.0.0.1", instanceConfig.getIpAddress());
Assertions.assertEquals("default", instanceConfig.getAppname());
@@ -104,7 +105,7 @@ public class EurekaRegistryServiceImplTest {
void testRegisterWhenEurekaClientIsNull() throws Exception {
setStaticField(EurekaRegistryServiceImpl.class, "eurekaClient", null);
InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8091);
- registryService.register(address);
+ registryService.register(new ServiceInstance(address));
verify(mockAppInfoManager, times(0)).setInstanceStatus(any());
}
@@ -153,7 +154,7 @@ public class EurekaRegistryServiceImplTest {
@Test
public void testUnregister() throws Exception {
- registryService.unregister(new InetSocketAddress("127.0.0.1", 8091));
+ registryService.unregister(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091)));
verify(mockAppInfoManager).setInstanceStatus(InstanceInfo.InstanceStatus.DOWN);
}
@@ -172,16 +173,17 @@ public class EurekaRegistryServiceImplTest {
when(mockInstanceInfo.getIPAddr()).thenReturn("192.168.1.1");
when(mockInstanceInfo.getPort()).thenReturn(8091);
- List<InetSocketAddress> addresses = registryService.lookup("test-group");
+ List<ServiceInstance> instances = registryService.lookup("test-group");
// Verify whether the transactionServiceGroup is set correctly
Field serviceGroupField = EurekaRegistryServiceImpl.class.getDeclaredField("transactionServiceGroup");
serviceGroupField.setAccessible(true);
String actualServiceGroup = (String) serviceGroupField.get(registryService);
Assertions.assertEquals("test-group", actualServiceGroup);
- Assertions.assertNotNull(addresses);
- Assertions.assertEquals(1, addresses.size());
- Assertions.assertEquals(new InetSocketAddress("192.168.1.1", 8091), addresses.get(0));
+ Assertions.assertNotNull(instances);
+ Assertions.assertEquals(1, instances.size());
+ Assertions.assertEquals(
+ new InetSocketAddress("192.168.1.1", 8091), instances.get(0).getAddress());
}
}
diff --git a/discovery/seata-discovery-eureka/src/test/resources/registry.conf b/discovery/seata-discovery-eureka/src/test/resources/registry.conf
index d229acd77c..a26c1367c5 100644
--- a/discovery/seata-discovery-eureka/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-eureka/src/test/resources/registry.conf
@@ -19,74 +19,17 @@ registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"
- nacos {
- application = "seata-server"
- serverAddr = "localhost"
- namespace = ""
- cluster = "default"
- }
eureka {
serviceUrl = "http://localhost:8761/eureka"
application = "default"
weight = "1"
}
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- consul {
- cluster = "default"
- serverAddr = "127.0.0.1:8500"
- }
- etcd3 {
- cluster = "default"
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- application = "default"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- cluster = "default"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
- file {
- name = "file.conf"
- }
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
- nacos {
- serverAddr = "localhost"
- namespace = ""
- group = "SEATA_GROUP"
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- }
- apollo {
- appId = "seata-server"
- apolloMeta = "http://192.168.1.204:8801"
- namespace = "application"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
file {
name = "file.conf"
}
diff --git a/discovery/seata-discovery-nacos/src/main/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java b/discovery/seata-discovery-nacos/src/main/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java
index 3edbd120c7..d0a1dc33de 100644
--- a/discovery/seata-discovery-nacos/src/main/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java
+++ b/discovery/seata-discovery-nacos/src/main/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImpl.java
@@ -23,6 +23,7 @@ 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 com.alibaba.nacos.api.naming.pojo.Service;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -36,8 +37,9 @@ import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -75,7 +77,7 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
private static final Configuration FILE_CONFIG = ConfigurationFactory.CURRENT_FILE_INSTANCE;
private static volatile NamingService naming;
private static final ConcurrentMap<String, List<EventListener>> LISTENER_SERVICE_MAP = new ConcurrentHashMap<>();
- private static final ConcurrentMap<String, List<InetSocketAddress>> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<String, List<ServiceInstance>> CLUSTER_INSTANCE_MAP = new ConcurrentHashMap<>();
private static volatile NacosRegistryServiceImpl instance;
private static volatile NamingMaintainService namingMaintain;
private static final Object LOCK_OBJ = new Object();
@@ -112,7 +114,8 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
getNamingInstance()
.registerInstance(
@@ -124,7 +127,8 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
getNamingInstance()
.deregisterInstance(
@@ -158,7 +162,7 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
transactionServiceGroup = key;
String clusterName = getServiceGroup(key);
if (clusterName == null) {
@@ -169,19 +173,21 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("look up service address of SLB by nacos");
}
- if (!CLUSTER_ADDRESS_MAP.containsKey(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName)) {
+ if (!CLUSTER_INSTANCE_MAP.containsKey(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName)) {
Service service = getNamingMaintainInstance().queryService(DEFAULT_APPLICATION, clusterName);
String pubnetIp = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_IP_KEY);
String pubnetPort = service.getMetadata().get(PUBLIC_NAMING_SERVICE_META_PORT_KEY);
if (StringUtils.isBlank(pubnetIp) || StringUtils.isBlank(pubnetPort)) {
throw new Exception("cannot find service address from nacos naming mata-data");
}
- InetSocketAddress publicAddress = new InetSocketAddress(pubnetIp, Integer.valueOf(pubnetPort));
- List<InetSocketAddress> publicAddressList = Arrays.asList(publicAddress);
- CLUSTER_ADDRESS_MAP.put(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName, publicAddressList);
- return publicAddressList;
+ InetSocketAddress publicAddress = new InetSocketAddress(pubnetIp, Integer.parseInt(pubnetPort));
+ Map<String, String> metadata = service.getMetadata();
+ List<ServiceInstance> publicInstanceList =
+ Collections.singletonList(ServiceInstance.fromStringMap(publicAddress, metadata));
+ CLUSTER_INSTANCE_MAP.put(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName, publicInstanceList);
+ return publicInstanceList;
}
- return CLUSTER_ADDRESS_MAP.get(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName);
+ return CLUSTER_INSTANCE_MAP.get(PUBLIC_NAMING_ADDRESS_PREFIX + clusterName);
}
if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) {
synchronized (LOCK_OBJ) {
@@ -191,33 +197,36 @@ public class NacosRegistryServiceImpl implements RegistryService<EventListener>
List<Instance> firstAllInstances =
getNamingInstance().getAllInstances(getServiceName(), getServiceGroup(), clusters);
if (null != firstAllInstances) {
- List<InetSocketAddress> newAddressList = firstAllInstances.stream()
+ List<ServiceInstance> newInstanceList = firstAllInstances.stream()
.filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy())
- .map(eachInstance ->
- new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort()))
+ .map(eachInstance -> ServiceInstance.fromStringMap(
+ new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort()),
+ eachInstance.getMetadata()))
.collect(Collectors.toList());
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ CLUSTER_INSTANCE_MAP.put(clusterName, newInstanceList);
}
subscribe(clusterName, event -> {
List<Instance> instances = ((NamingEvent) event).getInstances();
- if (CollectionUtils.isEmpty(instances) && null != CLUSTER_ADDRESS_MAP.get(clusterName)) {
+ if (CollectionUtils.isEmpty(instances) && null != CLUSTER_INSTANCE_MAP.get(clusterName)) {
LOGGER.info("receive empty server list,cluster:{}", clusterName);
} else {
- List<InetSocketAddress> newAddressList = instances.stream()
+ List<ServiceInstance> newInstanceList = instances.stream()
.filter(eachInstance -> eachInstance.isEnabled() && eachInstance.isHealthy())
- .map(eachInstance ->
- new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort()))
+ .map(eachInstance -> ServiceInstance.fromStringMap(
+ new InetSocketAddress(eachInstance.getIp(), eachInstance.getPort()),
+ eachInstance.getMetadata()))
.collect(Collectors.toList());
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ CLUSTER_INSTANCE_MAP.put(clusterName, newInstanceList);
if (StringUtils.isNotEmpty(transactionServiceGroup)) {
- removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newAddressList);
+ removeOfflineAddressesIfNecessary(
+ transactionServiceGroup, clusterName, newInstanceList);
}
}
});
}
}
}
- return CLUSTER_ADDRESS_MAP.get(clusterName);
+ return CLUSTER_INSTANCE_MAP.get(clusterName);
}
@Override
diff --git a/discovery/seata-discovery-nacos/src/test/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImplTest.java b/discovery/seata-discovery-nacos/src/test/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImplTest.java
index 360e11f7ba..344942a35d 100644
--- a/discovery/seata-discovery-nacos/src/test/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImplTest.java
+++ b/discovery/seata-discovery-nacos/src/test/java/org/apache/seata/discovery/registry/nacos/NacosRegistryServiceImplTest.java
@@ -28,7 +28,6 @@ import static org.junit.jupiter.api.Assertions.assertNull;
/**
* The type Nacos registry serivce impl test
- *
*/
public class NacosRegistryServiceImplTest {
diff --git a/discovery/seata-discovery-nacos/src/test/resources/registry.conf b/discovery/seata-discovery-nacos/src/test/resources/registry.conf
index 1fbdb5694b..1fd13bc940 100644
--- a/discovery/seata-discovery-nacos/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-nacos/src/test/resources/registry.conf
@@ -33,88 +33,13 @@ registry {
##if use Nacos naming meta-data for SLB service registry, specify nacos address pattern rules here
#slbPattern = ""
}
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- password = ""
- timeout = "0"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- username = ""
- password = ""
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- aclToken = ""
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
- file {
- name = "file.conf"
- }
- custom {
- name = ""
- }
}
config {
# file、nacos 、apollo、zk、consul、etcd3、springCloudConfig、custom
type = "file"
- nacos {
- serverAddr = "127.0.0.1:8848"
- namespace = ""
- group = "SEATA_GROUP"
- username = ""
- password = ""
- contextPath = "/bar"
- ##if use MSE Nacos with auth, mutex with username/password attribute
- #accessKey = ""
- #secretKey = ""
- dataId = "seata.properties"
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- key = "seata.properties"
- aclToken = ""
- }
- apollo {
- appId = "seata-server"
- apolloMeta = "http://192.168.1.204:8801"
- namespace = "application"
- apolloAccesskeySecret = ""
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- username = ""
- password = ""
- nodePath = "/seata/seata.properties"
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- key = "seata.properties"
- }
file {
name = "file.conf"
}
- custom {
- name = ""
- }
}
diff --git a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingListener.java b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingListener.java
index e4e07417d8..3406b69323 100644
--- a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingListener.java
+++ b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingListener.java
@@ -16,11 +16,15 @@
*/
package org.apache.seata.discovery.registry.namingserver;
+/**
+ * Listener interface for namingserver events.
+ */
public interface NamingListener {
+
/**
- * on event
+ * Called when a namingserver event occurs.
*
- * @param vGroup
+ * @param vGroup the vGroup
*/
void onEvent(String vGroup);
}
diff --git a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingRegistryException.java b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingRegistryException.java
index ff44364bcf..e7c2c4b9ba 100644
--- a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingRegistryException.java
+++ b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingRegistryException.java
@@ -16,10 +16,13 @@
*/
package org.apache.seata.discovery.registry.namingserver;
+/**
+ * Exception thrown when namingserver registry fail.
+ */
public class NamingRegistryException extends RuntimeException {
/**
- * naming registry exception.
+ * Creates an exception with message.
*
* @param message the message
*/
diff --git a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java
index cfb267ec1f..335a0765b9 100644
--- a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java
+++ b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java
@@ -20,8 +20,17 @@ import org.apache.seata.common.loader.LoadLevel;
import org.apache.seata.discovery.registry.RegistryProvider;
import org.apache.seata.discovery.registry.RegistryService;
+/**
+ * Registry provider for namingserver.
+ */
@LoadLevel(name = "Seata", order = 1)
public class NamingserverRegistryProvider implements RegistryProvider {
+
+ /**
+ * Provides the namingserver registryService instance.
+ *
+ * @return the namingserver registryService
+ */
@Override
public RegistryService provide() {
return NamingserverRegistryServiceImpl.getInstance();
diff --git a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImpl.java b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImpl.java
index 9fe99573f9..5773c9afde 100644
--- a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImpl.java
+++ b/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImpl.java
@@ -33,6 +33,7 @@ import org.apache.seata.common.metadata.Cluster;
import org.apache.seata.common.metadata.ClusterRole;
import org.apache.seata.common.metadata.Instance;
import org.apache.seata.common.metadata.Node;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.metadata.namingserver.MetaResponse;
import org.apache.seata.common.metadata.namingserver.NamingServerNode;
import org.apache.seata.common.metadata.namingserver.Unit;
@@ -71,58 +72,56 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
+/**
+ * Namingserver registryService implementation.
+ */
public class NamingserverRegistryServiceImpl implements RegistryService<NamingListener> {
private static final Logger LOGGER = LoggerFactory.getLogger(NamingserverRegistryServiceImpl.class);
-
public static volatile NamingserverRegistryServiceImpl instance;
- private static final String NAMESPACE_KEY = "namespace";
- private static final String VGROUP_KEY = "vGroup";
- private static final String CLIENT_TERM_KEY = "clientTerm";
- private static final String DEFAULT_NAMESPACE = "public";
- private static final String NAMING_SERVICE_URL_KEY = "server-addr";
+
private static final String FILE_ROOT_REGISTRY = "registry";
private static final String FILE_CONFIG_SPLIT_CHAR = ".";
private static final String REGISTRY_TYPE = "seata";
+
+ private static final String NAMESPACE_KEY = "namespace";
+ private static final String VGROUP_KEY = "vGroup";
private static final String HTTP_PREFIX = "http://";
- private static final String TIME_OUT_KEY = "timeout";
- private static final String PRO_USERNAME_KEY = "username";
+ private static final String PRO_USERNAME_KEY = "username";
private static final String PRO_PASSWORD_KEY = "password";
+ private static final String AUTHORIZATION_HEADER = "Authorization";
+ private static final String TOKEN_VALID_TIME_MS_KEY = "tokenValidityInMilliseconds";
private static final String META_DATA_MAX_AGE_MS = "metadataMaxAgeMs";
- private static final String AUTHORIZATION_HEADER = "Authorization";
+ private static final long TOKEN_EXPIRE_TIME_IN_MILLISECONDS;
- private static final String TOKEN_VALID_TIME_MS_KEY = "tokenValidityInMilliseconds";
+ private static int healthcheckPeriod = 5 * 1000;
+ private static final int LONG_POLL_TIME_OUT_PERIOD = 28 * 1000;
- private static final long TOKEN_EXPIRE_TIME_IN_MILLISECONDS;
+ private static final int THREAD_POOL_NUM = 1;
+ // namingserver is considered unhealthy if failing in healthy check more than 1 times
+ private static final int HEALTH_CHECK_THRESHOLD = 1;
private static final String USERNAME;
-
private static final String PASSWORD;
-
public static String jwtToken;
-
private static long tokenTimeStamp = -1;
- private static final String HEART_BEAT_KEY = "heartbeat-period";
- private static int healthcheckPeriod = 5 * 1000;
- private static final int LONG_POLL_TIME_OUT_PERIOD = 28 * 1000;
- private static final int THREAD_POOL_NUM = 1;
- private static final int HEALTH_CHECK_THRESHOLD =
- 1; // namingserver is considered unhealthy if failing in healthy check more than 1 times
private volatile long term = 0;
- private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private volatile boolean isSubscribed = false;
- private static final Configuration FILE_CONFIG = ConfigurationFactory.CURRENT_FILE_INSTANCE;
private String namingServerAddressCache;
- private static final ConcurrentMap<
- String /* namingserver address */, AtomicInteger /* Number of Health Check Continues Failures */>
- AVAILABLE_NAMINGSERVER_MAP = new ConcurrentHashMap<>();
+
+ private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
+ private static final Configuration FILE_CONFIG = ConfigurationFactory.CURRENT_FILE_INSTANCE;
+
+ // k: naming server address; v: Number of Health Check Continues Failures
+ private static final ConcurrentMap<String, AtomicInteger> AVAILABLE_NAMINGSERVER_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String /* vgroup */, List<NamingServerNode>> VGROUP_ADDRESS_MAP =
new ConcurrentHashMap<>();
private static final ConcurrentMap<String /* vgroup */, List<NamingListener>> LISTENER_SERVICE_MAP =
new ConcurrentHashMap<>();
+
protected static final ScheduledExecutorService SCHEDULED_THREAD_POOL_EXECUTOR = new ScheduledThreadPoolExecutor(
1, new NamedThreadFactory("seata-namingser-scheduled", THREAD_POOL_NUM, true));
private static final ExecutorService NOTIFIER_EXECUTOR = new ThreadPoolExecutor(
@@ -143,7 +142,8 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
private NamingserverRegistryServiceImpl() {
OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- String heartBeatKey = String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, HEART_BEAT_KEY);
+ String heartBeatKey =
+ String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, "heartbeat-period");
healthcheckPeriod = FILE_CONFIG.getInt(heartBeatKey, healthcheckPeriod);
List<String> urlList = getNamingAddrs();
checkAvailableNamingAddr(urlList);
@@ -175,13 +175,19 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
}
- /**
- * Gets instance.
- *
- * @return the instance
- */
- static NamingserverRegistryServiceImpl getInstance() {
+ public boolean doHealthCheck(String url) {
+ url = HTTP_PREFIX + url + "/naming/v1/health";
+ Map<String, String> header = new HashMap<>();
+ header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
+ try (CloseableHttpResponse response = HttpClientUtil.doGet(url, null, header, 3000)) {
+ int statusCode = response.getStatusLine().getStatusCode();
+ return statusCode == 200;
+ } catch (Exception e) {
+ return false;
+ }
+ }
+ static NamingserverRegistryServiceImpl getInstance() {
if (instance == null) {
synchronized (NamingserverRegistryServiceImpl.class) {
if (instance == null) {
@@ -193,18 +199,12 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
@Override
- public void register(InetSocketAddress address) throws Exception {
- register(Instance.getInstance());
- }
-
- @Override
- public void register(Instance instance) throws Exception {
+ public void register(ServiceInstance serviceInstance) throws Exception {
+ Instance instance = Instance.getInstance();
instance.setTimestamp(System.currentTimeMillis());
doRegister(instance, getNamingAddrs());
}
- public void doRegister(List<Instance> instance, List<String> urlList) {}
-
public void doRegister(Instance instance, List<String> urlList) throws RetryableException {
for (String urlSuffix : urlList) {
// continue if name server node is unhealthy
@@ -245,25 +245,9 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
}
- public boolean doHealthCheck(String url) {
- url = HTTP_PREFIX + url + "/naming/v1/health";
- Map<String, String> header = new HashMap<>();
- header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
- try (CloseableHttpResponse response = HttpClientUtil.doGet(url, null, header, 3000)) {
- int statusCode = response.getStatusLine().getStatusCode();
- return statusCode == 200;
- } catch (Exception e) {
- return false;
- }
- }
-
- @Override
- public void unregister(InetSocketAddress inetSocketAddress) {
- unregister(Instance.getInstance());
- }
-
@Override
- public void unregister(Instance instance) {
+ public void unregister(ServiceInstance serviceInstance) {
+ Instance instance = Instance.getInstance();
for (String urlSuffix : getNamingAddrs()) {
String url = HTTP_PREFIX + urlSuffix + "/naming/v1/unregister?";
String unit = instance.getUnit();
@@ -288,9 +272,9 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
@Override
- public void subscribe(String cluster, NamingListener listener) throws Exception {}
+ public void subscribe(String cluster, NamingListener listener) {}
- public void subscribe(NamingListener listener, String vGroup) throws Exception {
+ public void subscribe(NamingListener listener, String vGroup) {
LISTENER_SERVICE_MAP.computeIfAbsent(vGroup, key -> new ArrayList<>()).add(listener);
isSubscribed = true;
NOTIFIER_EXECUTOR.execute(() -> {
@@ -343,11 +327,11 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
.append("=")
.append(vGroup)
.append("&")
- .append(CLIENT_TERM_KEY)
+ .append("clientTerm")
.append("=")
.append(term)
.append("&")
- .append(TIME_OUT_KEY)
+ .append("timeout")
.append("=")
.append(LONG_POLL_TIME_OUT_PERIOD)
.append("&clientAddr=")
@@ -373,9 +357,9 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
@Override
- public void unsubscribe(String cluster, NamingListener listener) throws Exception {}
+ public void unsubscribe(String cluster, NamingListener listener) {}
- public void unsubscribe(NamingListener listener, String vGroup) throws Exception {
+ public void unsubscribe(NamingListener listener, String vGroup) {
// remove watchers
List<NamingListener> listeners = LISTENER_SERVICE_MAP.get(vGroup);
if (listeners != null) {
@@ -389,18 +373,8 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
isSubscribed = false;
}
- public void unsubscribe(String vGroup) throws Exception {
- LISTENER_SERVICE_MAP.remove(vGroup);
- isSubscribed = false;
- }
-
- /**
- * @param key vGroup name
- * @return List<InetSocketAddress> available instance list
- * @throws Exception
- */
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
if (!isSubscribed) {
// get available instanceList by vGroup
refreshGroup(key);
@@ -419,12 +393,13 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
return Optional.ofNullable(VGROUP_ADDRESS_MAP.get(key)).orElse(Collections.emptyList()).stream()
.map(node -> {
Node.Endpoint endpoint = node.getTransaction();
- return new InetSocketAddress(endpoint.getHost(), endpoint.getPort());
+ Map<String, Object> metadata = node.getMetadata();
+ return new ServiceInstance(new InetSocketAddress(endpoint.getHost(), endpoint.getPort()), metadata);
})
.collect(Collectors.toList());
}
- public List<InetSocketAddress> refreshGroup(String vGroup) throws IOException, RetryableException {
+ private List<ServiceInstance> refreshGroup(String vGroup) throws IOException, RetryableException {
Map<String, String> paraMap = new HashMap<>();
String namingAddr = getNamingAddr();
if (isTokenExpired()) {
@@ -453,7 +428,7 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
}
- public List<InetSocketAddress> handleMetadata(MetaResponse metaResponse, String vGroup) {
+ private List<ServiceInstance> handleMetadata(MetaResponse metaResponse, String vGroup) {
// MetaResponse -> endpoint list
List<NamingServerNode> newAddressList = new ArrayList<>();
if (metaResponse.getTerm() > 0) {
@@ -468,14 +443,15 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
.collect(Collectors.toList()));
}
}
- List<InetSocketAddress> inetSocketAddresses = new ArrayList<>();
+ List<ServiceInstance> serviceInstances = new ArrayList<>();
for (NamingServerNode node : newAddressList) {
Node.Endpoint endpoint = node.getTransaction();
- inetSocketAddresses.add(new InetSocketAddress(endpoint.getHost(), endpoint.getPort()));
+ serviceInstances.add(new ServiceInstance(
+ new InetSocketAddress(endpoint.getHost(), endpoint.getPort()), node.getMetadata()));
}
- removeOfflineAddressesIfNecessary(vGroup, vGroup, inetSocketAddresses);
+ removeOfflineAddressesIfNecessary(vGroup, vGroup, serviceInstances);
VGROUP_ADDRESS_MAP.put(vGroup, newAddressList);
- return inetSocketAddresses;
+ return serviceInstances;
}
@Override
@@ -486,23 +462,14 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
return RegistryService.super.getServiceGroup(key);
}
- public String getNamespace() {
- String namespaceKey = String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, NAMESPACE_KEY);
- String namespace = FILE_CONFIG.getConfig(namespaceKey);
- if (StringUtils.isBlank(namespace)) {
- namespace = DEFAULT_NAMESPACE;
- }
- return namespace;
- }
-
@Override
- public List<InetSocketAddress> aliveLookup(String transactionServiceGroup) {
- Map<String, List<InetSocketAddress>> clusterAddressMap =
- CURRENT_ADDRESS_MAP.computeIfAbsent(transactionServiceGroup, k -> new ConcurrentHashMap<>());
+ public List<ServiceInstance> aliveLookup(String transactionServiceGroup) {
+ Map<String, List<ServiceInstance>> clusterAddressMap =
+ CURRENT_INSTANCE_MAP.computeIfAbsent(transactionServiceGroup, k -> new ConcurrentHashMap<>());
- List<InetSocketAddress> inetSocketAddresses = clusterAddressMap.get(transactionServiceGroup);
- if (CollectionUtils.isNotEmpty(inetSocketAddresses)) {
- return inetSocketAddresses;
+ List<ServiceInstance> serviceInstances = clusterAddressMap.get(transactionServiceGroup);
+ if (CollectionUtils.isNotEmpty(serviceInstances)) {
+ return serviceInstances;
}
// fall back to addresses of any cluster
@@ -513,55 +480,11 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
}
@Override
- public List<InetSocketAddress> refreshAliveLookup(
- String transactionServiceGroup, List<InetSocketAddress> aliveAddress) {
- Map<String, List<InetSocketAddress>> clusterAddressMap =
- CURRENT_ADDRESS_MAP.computeIfAbsent(transactionServiceGroup, key -> new ConcurrentHashMap<>());
- return clusterAddressMap.put(transactionServiceGroup, aliveAddress);
- }
-
- /**
- * get one namingserver url
- *
- * @return url
- */
- public String getNamingAddr() {
- if (namingServerAddressCache != null) {
- return namingServerAddressCache;
- }
- Map<String, AtomicInteger> availableNamingserverMap = new HashMap<>(AVAILABLE_NAMINGSERVER_MAP);
- List<String> availableNamingserverList = new ArrayList<>();
- for (Map.Entry<String, AtomicInteger> entry : availableNamingserverMap.entrySet()) {
- String namingServerAddress = entry.getKey();
- Integer numberOfFailures = entry.getValue().get();
-
- if (numberOfFailures < HEALTH_CHECK_THRESHOLD) {
- availableNamingserverList.add(namingServerAddress);
- }
- }
- if (availableNamingserverList.isEmpty()) {
- throw new NamingRegistryException("no available namingserver address!");
- } else {
- namingServerAddressCache = availableNamingserverList.get(
- ThreadLocalRandom.current().nextInt(availableNamingserverList.size()));
- return namingServerAddressCache;
- }
- }
-
- /**
- * get all namingserver urlList
- *
- * @return url List
- */
- public List<String> getNamingAddrs() {
- String namingAddrsKey =
- String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, NAMING_SERVICE_URL_KEY);
-
- String urlListStr = FILE_CONFIG.getConfig(namingAddrsKey);
- if (StringUtils.isBlank(urlListStr)) {
- throw new NamingRegistryException("Naming server url can not be null!");
- }
- return Arrays.stream(urlListStr.split(",")).collect(Collectors.toList());
+ public List<ServiceInstance> refreshAliveLookup(
+ String transactionServiceGroup, List<ServiceInstance> aliveInstances) {
+ Map<String, List<ServiceInstance>> clusterInstanceMap =
+ CURRENT_INSTANCE_MAP.computeIfAbsent(transactionServiceGroup, key -> new ConcurrentHashMap<>());
+ return clusterInstanceMap.put(transactionServiceGroup, aliveInstances);
}
private static void refreshToken(String tcAddress) throws RetryableException {
@@ -617,6 +540,58 @@ public class NamingserverRegistryServiceImpl implements RegistryService<NamingLi
return System.currentTimeMillis() >= tokenExpiredTime;
}
+ /**
+ * Get a single available namingserver address with health check and load balancing.
+ *
+ * @return a randomly selected healthy naming server address
+ */
+ private String getNamingAddr() {
+ if (namingServerAddressCache != null) {
+ return namingServerAddressCache;
+ }
+ Map<String, AtomicInteger> availableNamingserverMap = new HashMap<>(AVAILABLE_NAMINGSERVER_MAP);
+ List<String> availableNamingserverList = new ArrayList<>();
+ for (Map.Entry<String, AtomicInteger> entry : availableNamingserverMap.entrySet()) {
+ String namingServerAddress = entry.getKey();
+ Integer numberOfFailures = entry.getValue().get();
+
+ if (numberOfFailures < HEALTH_CHECK_THRESHOLD) {
+ availableNamingserverList.add(namingServerAddress);
+ }
+ }
+ if (availableNamingserverList.isEmpty()) {
+ throw new NamingRegistryException("no available namingserver address!");
+ } else {
+ namingServerAddressCache = availableNamingserverList.get(
+ ThreadLocalRandom.current().nextInt(availableNamingserverList.size()));
+ return namingServerAddressCache;
+ }
+ }
+
+ /**
+ * Get all configured namingserver addresses from configuration file without health check.
+ *
+ * @return list of all configured naming server addresses
+ */
+ private List<String> getNamingAddrs() {
+ String namingAddrsKey = String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, "server-addr");
+
+ String urlListStr = FILE_CONFIG.getConfig(namingAddrsKey);
+ if (StringUtils.isBlank(urlListStr)) {
+ throw new NamingRegistryException("Naming server url can not be null!");
+ }
+ return Arrays.stream(urlListStr.split(",")).collect(Collectors.toList());
+ }
+
+ private String getNamespace() {
+ String namespaceKey = String.join(FILE_CONFIG_SPLIT_CHAR, FILE_ROOT_REGISTRY, REGISTRY_TYPE, NAMESPACE_KEY);
+ String namespace = FILE_CONFIG.getConfig(namespaceKey);
+ if (StringUtils.isBlank(namespace)) {
+ namespace = "public";
+ }
+ return namespace;
+ }
+
private static String getUserNameKey() {
return String.join(
ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR,
diff --git a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProviderTest.java
similarity index 68%
copy from discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java
copy to discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProviderTest.java
index cfb267ec1f..586b98a782 100644
--- a/discovery/seata-discovery-namingserver/src/main/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProvider.java
+++ b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryProviderTest.java
@@ -16,14 +16,17 @@
*/
package org.apache.seata.discovery.registry.namingserver;
-import org.apache.seata.common.loader.LoadLevel;
-import org.apache.seata.discovery.registry.RegistryProvider;
-import org.apache.seata.discovery.registry.RegistryService;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
-@LoadLevel(name = "Seata", order = 1)
-public class NamingserverRegistryProvider implements RegistryProvider {
- @Override
- public RegistryService provide() {
- return NamingserverRegistryServiceImpl.getInstance();
+/**
+ * Test for NamingserverRegistryProvider
+ */
+public class NamingserverRegistryProviderTest {
+
+ @Test
+ public void testProvide() {
+ NamingserverRegistryProvider provider = new NamingserverRegistryProvider();
+ Assertions.assertInstanceOf(NamingserverRegistryServiceImpl.class, provider.provide());
}
}
diff --git a/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplMockTest.java b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplMockTest.java
new file mode 100644
index 0000000000..a982f0df7d
--- /dev/null
+++ b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplMockTest.java
@@ -0,0 +1,276 @@
+/*
+ * 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.seata.discovery.registry.namingserver;
+
+import org.apache.seata.common.metadata.Cluster;
+import org.apache.seata.common.metadata.ClusterRole;
+import org.apache.seata.common.metadata.Instance;
+import org.apache.seata.common.metadata.Node;
+import org.apache.seata.common.metadata.ServiceInstance;
+import org.apache.seata.common.metadata.namingserver.MetaResponse;
+import org.apache.seata.common.metadata.namingserver.NamingServerNode;
+import org.apache.seata.common.metadata.namingserver.Unit;
+import org.apache.seata.config.Configuration;
+import org.apache.seata.config.ConfigurationFactory;
+import org.apache.seata.discovery.registry.RegistryService;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+import org.mockito.MockitoAnnotations;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Mock test for NamingserverRegistryServiceImpl
+ */
+public class NamingserverRegistryServiceImplMockTest {
+
+ private NamingserverRegistryServiceImpl registryService;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ MockitoAnnotations.openMocks(this);
+ registryService = NamingserverRegistryServiceImpl.getInstance();
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ // Clean up static maps to avoid test interference
+ Field listenerMapField = NamingserverRegistryServiceImpl.class.getDeclaredField("LISTENER_SERVICE_MAP");
+ listenerMapField.setAccessible(true);
+
+ @SuppressWarnings("unchecked")
+ Map<String, List<NamingListener>> listenerMap = (Map<String, List<NamingListener>>) listenerMapField.get(null);
+ listenerMap.clear();
+
+ Field currentInstanceMapField = RegistryService.class.getDeclaredField("CURRENT_INSTANCE_MAP");
+ currentInstanceMapField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ Map<String, Map<String, List<ServiceInstance>>> currentInstanceMap =
+ (Map<String, Map<String, List<ServiceInstance>>>) currentInstanceMapField.get(null);
+ currentInstanceMap.clear();
+
+ // Reset isSubscribed field
+ Field isSubscribedField = NamingserverRegistryServiceImpl.class.getDeclaredField("isSubscribed");
+ isSubscribedField.setAccessible(true);
+ isSubscribedField.set(registryService, false);
+ }
+
+ @Test
+ public void testGetInstance() {
+ NamingserverRegistryServiceImpl instance = NamingserverRegistryServiceImpl.getInstance();
+ assertInstanceOf(NamingserverRegistryServiceImpl.class, instance);
+ }
+
+ @Test
+ public void testRegister() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091));
+
+ Instance mockInstance = mock(Instance.class);
+ when(mockInstance.getNamespace()).thenReturn("test-namespace");
+ when(mockInstance.getClusterName()).thenReturn("test-cluster");
+ when(mockInstance.getUnit()).thenReturn("test-unit");
+ when(mockInstance.getTransaction()).thenReturn(new Node.Endpoint("127.0.0.1", 8091));
+ when(mockInstance.getMetadata()).thenReturn(new HashMap<>());
+ when(mockInstance.toJsonString(any())).thenReturn("{\"test\":\"value\"}");
+
+ try (MockedStatic<Instance> mockedInstance = Mockito.mockStatic(Instance.class)) {
+ mockedInstance.when(Instance::getInstance).thenReturn(mockInstance);
+
+ registryService.register(serviceInstance);
+
+ verify(mockInstance).setTimestamp(any(Long.class));
+ }
+ }
+
+ @Test
+ public void testUnregister() {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091));
+
+ Instance mockInstance = mock(Instance.class);
+ when(mockInstance.getNamespace()).thenReturn("test-namespace");
+ when(mockInstance.getClusterName()).thenReturn("test-cluster");
+ when(mockInstance.getUnit()).thenReturn("test-unit");
+ when(mockInstance.getTransaction()).thenReturn(new Node.Endpoint("127.0.0.1", 8091));
+ when(mockInstance.getMetadata()).thenReturn(new HashMap<>());
+ when(mockInstance.toJsonString(any())).thenReturn("{\"test\":\"value\"}");
+
+ try (MockedStatic<Instance> mockedInstance = Mockito.mockStatic(Instance.class)) {
+ mockedInstance.when(Instance::getInstance).thenReturn(mockInstance);
+
+ registryService.unregister(serviceInstance);
+
+ verify(mockInstance).getUnit();
+ verify(mockInstance).toJsonString(any());
+ verify(mockInstance).getClusterName();
+ verify(mockInstance).getNamespace();
+ }
+ }
+
+ @Test
+ public void testHandleMetadata_withMockResponse() throws Exception {
+ // Use reflection to set the isSubscribed field to true
+ Field isSubscribedField = NamingserverRegistryServiceImpl.class.getDeclaredField("isSubscribed");
+ isSubscribedField.setAccessible(true);
+ isSubscribedField.set(registryService, true);
+
+ // Create a mock MetaResponse
+ MetaResponse metaResponse = new MetaResponse();
+ metaResponse.setTerm(1);
+
+ Cluster cluster = new Cluster();
+ Unit unit = new Unit();
+ List<NamingServerNode> namingInstanceList = new ArrayList<>();
+ NamingServerNode node = new NamingServerNode();
+ node.setRole(ClusterRole.LEADER);
+ node.setTerm(1);
+ node.setTransaction(new Node.Endpoint("127.0.0.1", 8091));
+ namingInstanceList.add(node);
+ unit.setNamingInstanceList(namingInstanceList);
+ List<Unit> unitData = new ArrayList<>();
+ unitData.add(unit);
+ cluster.setUnitData(unitData);
+ List<Cluster> clusterList = new ArrayList<>();
+ clusterList.add(cluster);
+ metaResponse.setClusterList(clusterList);
+
+ // Call the method to test
+ Method handleMetadataMethod =
+ registryService.getClass().getDeclaredMethod("handleMetadata", MetaResponse.class, String.class);
+ handleMetadataMethod.setAccessible(true);
+ List<ServiceInstance> result =
+ (List<ServiceInstance>) handleMetadataMethod.invoke(registryService, metaResponse, "testGroup");
+
+ registryService.lookup("testGroup");
+
+ // Verify the result
+ assertEquals(1, result.size());
+ assertEquals("127.0.0.1", result.get(0).getAddress().getAddress().getHostAddress());
+ assertEquals(8091, result.get(0).getAddress().getPort());
+ isSubscribedField.set(registryService, false);
+ }
+
+ @Test
+ public void testSubscribeAndUnsubscribe() throws Exception {
+ NamingListener mockListener = mock(NamingListener.class);
+ String vGroup = "test-vgroup";
+
+ registryService.subscribe(mockListener, vGroup);
+
+ // Verify that the listener was added to the map
+ Field listenerMapField = NamingserverRegistryServiceImpl.class.getDeclaredField("LISTENER_SERVICE_MAP");
+ listenerMapField.setAccessible(true);
+ @SuppressWarnings("unchecked")
+ Map<String, List<NamingListener>> listenerMap = (Map<String, List<NamingListener>>) listenerMapField.get(null);
+
+ assertNotNull(listenerMap);
+ assertTrue(listenerMap.containsKey(vGroup));
+ List<NamingListener> listeners = listenerMap.get(vGroup);
+ assertNotNull(listeners);
+ assertTrue(listeners.contains(mockListener));
+
+ registryService.unsubscribe(mockListener, vGroup);
+
+ assertFalse(listenerMap.containsKey(vGroup));
+ }
+
+ @Test
+ public void testRefreshAliveLookup() {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091));
+ String transactionServiceGroup = "test-group";
+
+ // Test refreshAliveLookup with a list of instances
+ List<ServiceInstance> instances = Collections.singletonList(serviceInstance);
+ registryService.refreshAliveLookup(transactionServiceGroup, instances);
+
+ assertEquals(1, instances.size());
+ assertEquals("127.0.0.1", instances.get(0).getAddress().getAddress().getHostAddress());
+ assertEquals(8091, instances.get(0).getAddress().getPort());
+ }
+
+ @Test
+ public void testEmptyMethod() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091));
+ NamingListener mockListener = mock(NamingListener.class);
+
+ registryService.register(serviceInstance);
+
+ registryService.unregister(serviceInstance);
+
+ registryService.subscribe("test-cluster", mockListener);
+
+ registryService.unsubscribe("test-cluster", mockListener);
+
+ registryService.close();
+ }
+
+ @Test
+ public void testGetNamespace() throws Exception {
+ System.setProperty("registry.seata.namespace", "dev");
+
+ Method getNamespaceMethod = NamingserverRegistryServiceImpl.class.getDeclaredMethod("getNamespace");
+ getNamespaceMethod.setAccessible(true);
+ String result = (String) getNamespaceMethod.invoke(registryService);
+
+ assertEquals("dev", result);
+
+ System.clearProperty("registry.seata.namespace");
+ }
+
+ @Test
+ public void testGetMetadataMaxAgeMs() throws Exception {
+ Method getMetadataMaxAgeMsMethod =
+ NamingserverRegistryServiceImpl.class.getDeclaredMethod("getMetadataMaxAgeMs");
+ getMetadataMaxAgeMsMethod.setAccessible(true);
+ String result = (String) getMetadataMaxAgeMsMethod.invoke(registryService);
+
+ assertEquals("registry.seata.metadataMaxAgeMs", result);
+ }
+
+ @Test
+ public void testGetServiceGroup() {
+ Configuration mockConfig = mock(Configuration.class);
+ when(mockConfig.getConfig("service.vgroupMapping.test-key")).thenReturn("test-cluster");
+
+ try (MockedStatic<ConfigurationFactory> mockedFactory = mockStatic(ConfigurationFactory.class)) {
+ mockedFactory.when(ConfigurationFactory::getInstance).thenReturn(mockConfig);
+
+ String result = registryService.getServiceGroup("test-key");
+ assertEquals("test-cluster", result);
+ }
+ }
+}
diff --git a/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplTest.java b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplTest.java
index 46ac55ff35..5a49604a03 100644
--- a/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplTest.java
+++ b/discovery/seata-discovery-namingserver/src/test/java/org/apache/seata/discovery/registry/namingserver/NamingserverRegistryServiceImplTest.java
@@ -16,20 +16,10 @@
*/
package org.apache.seata.discovery.registry.namingserver;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.entity.ContentType;
-import org.apache.http.protocol.HTTP;
import org.apache.seata.common.holder.ObjectHolder;
-import org.apache.seata.common.metadata.Cluster;
-import org.apache.seata.common.metadata.ClusterRole;
+import org.apache.seata.common.metadata.Instance;
import org.apache.seata.common.metadata.Node;
-import org.apache.seata.common.metadata.namingserver.MetaResponse;
-import org.apache.seata.common.metadata.namingserver.NamingServerNode;
-import org.apache.seata.common.metadata.namingserver.Unit;
-import org.apache.seata.common.util.HttpClientUtil;
-import org.apache.seata.config.Configuration;
-import org.apache.seata.config.ConfigurationFactory;
-import org.apache.seata.discovery.registry.RegistryService;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
@@ -40,37 +30,60 @@ import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import java.lang.reflect.Field;
+import java.lang.reflect.Method;
import java.net.InetSocketAddress;
-import java.rmi.RemoteException;
-import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.ConcurrentMap;
import static org.apache.seata.common.Constants.OBJECT_KEY_SPRING_CONFIGURABLE_ENVIRONMENT;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+/**
+ * Test for NamingserverRegistryServiceImpl
+ * The @Disable annotation method requires local startup of namingserver for testing
+ */
class NamingserverRegistryServiceImplTest {
-
- private static final Configuration FILE_CONFIG = ConfigurationFactory.CURRENT_FILE_INSTANCE;
+ private final NamingserverRegistryServiceImpl registryService = NamingserverRegistryServiceImpl.getInstance();
@BeforeAll
- public static void beforeClass() throws Exception {
+ public static void beforeClass() {
+ // set the global instance information for the register
+ Instance instance = Instance.getInstance();
+ instance.setClusterName("cluster1");
+ instance.setUnit("unit1");
+ instance.setNamespace("dev");
+ instance.setTransaction(new Node.Endpoint("127.0.0.1", 8888));
+ instance.setControl(new Node.Endpoint("127.0.0.1", 8888));
+
+ Map<String, String> vGroups = new HashMap<>();
+ vGroups.put(
+ "group1",
+ "unit1"); // vGroup -> unitName, namingserver automatically adds transaction groups based on it
+ instance.addMetadata("vGroup", vGroups);
+
System.setProperty("registry.seata.namespace", "dev");
System.setProperty("registry.seata.cluster", "cluster1");
- System.setProperty("registry.seata.server-addr", "127.0.0.1:8080");
+ System.setProperty("registry.seata.server-addr", "127.0.0.1:8081");
+
+ System.setProperty("registry.seata.username", "seata");
+ System.setProperty("registry.seata.password", "seata");
+
+ // Set a smaller metadataMaxAgeMs for testing
+ System.setProperty("registry.seata.metadataMaxAgeMs", "1000");
+
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- // 获取应用程序环境
+ // Get the application environment
ConfigurableEnvironment environment = context.getEnvironment();
MutablePropertySources propertySources = environment.getPropertySources();
Properties customProperties = new Properties();
- customProperties.setProperty("seata.registry.namingserver.server-addr[0]", "127.0.0.1:8080");
+ customProperties.setProperty("seata.registry.namingserver.server-addr[0]", "127.0.0.1:8081");
PropertiesPropertySource customPropertySource = new PropertiesPropertySource("customSource", customProperties);
propertySources.addLast(customPropertySource);
@@ -82,292 +95,135 @@ class NamingserverRegistryServiceImplTest {
System.clearProperty("registry.seata.namespace");
System.clearProperty("registry.seata.cluster");
System.clearProperty("registry.seata.server-addr");
+ System.clearProperty("registry.seata.username");
+ System.clearProperty("registry.seata.password");
+ System.clearProperty("registry.seata.metadataMaxAgeMs");
}
@Test
- public void unregister1() throws Exception {
- NamingserverRegistryServiceImpl namingserverRegistryService = NamingserverRegistryServiceImpl.getInstance();
- InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8080);
- namingserverRegistryService.register(inetSocketAddress);
- namingserverRegistryService.unregister(inetSocketAddress);
- }
+ public void testGetNamingAddrs() throws Exception {
+ Method getNamingAddrsMethod = NamingserverRegistryServiceImpl.class.getDeclaredMethod("getNamingAddrs");
+ getNamingAddrsMethod.setAccessible(true);
- @Test
- @Disabled
- public void getNamingAddrsTest() {
- NamingserverRegistryServiceImpl namingserverRegistryService = NamingserverRegistryServiceImpl.getInstance();
- List<String> list = namingserverRegistryService.getNamingAddrs();
+ List<String> list = (List<String>) getNamingAddrsMethod.invoke(registryService);
assertEquals(list.size(), 1);
}
@Test
@Disabled
- public void getNamingAddrTest() {
- NamingserverRegistryServiceImpl namingserverRegistryService = NamingserverRegistryServiceImpl.getInstance();
- String addr = namingserverRegistryService.getNamingAddr();
- assertEquals(addr, "127.0.0.1:8080");
+ public void testGetNamingAddr() throws Exception {
+ Method getNamingAddrMethod = NamingserverRegistryServiceImpl.class.getDeclaredMethod("getNamingAddr");
+ getNamingAddrMethod.setAccessible(true);
+
+ String addr = (String) getNamingAddrMethod.invoke(registryService);
+ assertEquals(addr, "127.0.0.1:8081");
}
@Test
@Disabled
- public void testRegister1() throws Exception {
+ public void testRegisterAndUnregister() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8888));
- RegistryService registryService = new NamingserverRegistryProvider().provide();
+ // The ServiceInstance parameter here has no effect and is only used for assertion testing.
+ // In fact, register is registered by calling Instance.getInstance() of the global singleton.
+ registryService.register(serviceInstance);
- InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
- // 1.register
- registryService.register(inetSocketAddress1);
-
- // 2.create vGroup in cluster
- createGroupInCluster("dev", "group1", "cluster1");
- // 3.get instances
- List<InetSocketAddress> list = registryService.lookup("group1");
-
- assertEquals(list.size(), 1);
- InetSocketAddress inetSocketAddress = list.get(0);
- assertEquals(inetSocketAddress.getAddress().getHostAddress(), "127.0.0.1");
- assertEquals(inetSocketAddress.getPort(), 8088);
-
- registryService.unregister(inetSocketAddress1);
- }
-
- @Test
- public void testHandleMetadata() throws Exception {
- NamingserverRegistryServiceImpl registryService = NamingserverRegistryServiceImpl.getInstance();
- // Use reflection to set the isSubscribed field to true
- Field isSubscribedField = NamingserverRegistryServiceImpl.class.getDeclaredField("isSubscribed");
- isSubscribedField.setAccessible(true);
- isSubscribedField.set(registryService, true);
-
- // Create a mock MetaResponse
- MetaResponse metaResponse = new MetaResponse();
- metaResponse.setTerm(1);
-
- Cluster cluster = new Cluster();
- Unit unit = new Unit();
- List<NamingServerNode> namingInstanceList = new ArrayList<>();
- NamingServerNode node = new NamingServerNode();
- node.setRole(ClusterRole.LEADER);
- node.setTerm(1);
- node.setTransaction(new Node.Endpoint("127.0.0.1", 8091));
- namingInstanceList.add(node);
- unit.setNamingInstanceList(namingInstanceList);
- List<Unit> unitData = new ArrayList<>();
- unitData.add(unit);
- cluster.setUnitData(unitData);
- List<Cluster> clusterList = new ArrayList<>();
- clusterList.add(cluster);
- metaResponse.setClusterList(clusterList);
-
- // Call the method to test
- List<InetSocketAddress> result = registryService.handleMetadata(metaResponse, "testGroup");
- registryService.lookup("testGroup");
- // Verify the result
- assertEquals(1, result.size());
- assertEquals("127.0.0.1", result.get(0).getAddress().getHostAddress());
- assertEquals(8091, result.get(0).getPort());
- isSubscribedField.set(registryService, false);
- }
-
- @Test
- @Disabled
- public void testRegister2() throws Exception {
- NamingserverRegistryServiceImpl registryService =
- (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide();
- InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
- InetSocketAddress inetSocketAddress2 = new InetSocketAddress("127.0.0.1", 8088);
- // 1.register
- registryService.register(inetSocketAddress1);
- registryService.register(inetSocketAddress2);
-
- // 2.create vGroup in cluster
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group1", "cluster1");
-
- // 3.get instances
- List list = registryService.lookup("group1");
+ List<ServiceInstance> list = registryService.lookup("group1");
- assertEquals(list.size(), 1);
+ assertEquals(1, list.size());
+ Map<String, Object> metadata = new HashMap<>();
+ metadata.put("vGroup", Instance.getInstance().getMetadata().get("vGroup"));
+ serviceInstance.setMetadata(metadata);
- registryService.unregister(inetSocketAddress1);
- registryService.unregister(inetSocketAddress2);
- registryService.unsubscribe("group1");
- }
+ assertEquals(list.get(0), serviceInstance);
- @Test
- @Disabled
- public void testRegister3() throws Exception {
- NamingserverRegistryServiceImpl registryService =
- (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide();
- InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
- InetSocketAddress inetSocketAddress2 = new InetSocketAddress("127.0.0.1", 8089);
- InetSocketAddress inetSocketAddress3 = new InetSocketAddress("127.0.0.1", 8090);
- InetSocketAddress inetSocketAddress4 = new InetSocketAddress("127.0.0.1", 8091);
- // 1.register
- registryService.register(inetSocketAddress1);
- registryService.register(inetSocketAddress2);
- registryService.register(inetSocketAddress3);
- registryService.register(inetSocketAddress4);
-
- // 2.create vGroup in cluster
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group2", "cluster1");
-
- // 3.get instances
- List list = registryService.lookup("group2");
-
- assertEquals(list.size(), 4);
-
- registryService.unregister(inetSocketAddress1);
- registryService.unregister(inetSocketAddress2);
- registryService.unregister(inetSocketAddress3);
- registryService.unregister(inetSocketAddress4);
-
- registryService.unsubscribe("group2");
+ registryService.unregister(serviceInstance);
}
@Test
@Disabled
- public void testUnregister() throws Exception {
- RegistryService registryService = new NamingserverRegistryProvider().provide();
- InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
- // 1.register
- registryService.register(inetSocketAddress1);
+ public void testRegister_withMetadata() throws Exception {
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8888));
+ Instance.getInstance().addMetadata("key1", "value1");
+ Instance.getInstance().addMetadata("key2", Collections.singletonMap("subKey", "subValue"));
- // 2.create vGroup in cluster
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group1", "cluster1");
+ registryService.register(serviceInstance);
- // 3.get instances
- List list = registryService.lookup("group1");
+ List<ServiceInstance> list = registryService.lookup("group1");
- assertEquals(list.size(), 1);
+ assertEquals(1, list.size());
+ Map<String, Object> metadata = Instance.getInstance().getMetadata();
+ metadata.put("vGroup", Instance.getInstance().getMetadata().get("vGroup"));
+ serviceInstance.setMetadata(metadata);
- // 4.unregister
- registryService.unregister(inetSocketAddress1);
+ assertEquals(list.get(0), serviceInstance);
- // 5.get instances
- List list1 = registryService.lookup("group1");
- assertEquals(list1.size(), 0);
+ registryService.unregister(serviceInstance);
}
- @Disabled
@Test
- public void testWatch() throws Exception {
- NamingserverRegistryServiceImpl registryService =
- (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide();
-
- // 1.注册cluster1下的一个节点
- InetSocketAddress inetSocketAddress1 = new InetSocketAddress("127.0.0.1", 8088);
- registryService.register(inetSocketAddress1);
-
- ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
- int delaySeconds = 500;
- // 2.延迟0.5s后在cluster1下创建事务分组group1
- executor.schedule(
- () -> {
- try {
-
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group1", "cluster1");
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- executor.shutdown(); // 任务执行后关闭执行器
- },
- delaySeconds,
- TimeUnit.MILLISECONDS);
- // 3.watch事务分组group1
- long timestamp1 = System.currentTimeMillis();
- boolean needFetch = registryService.watch("group1");
- long timestamp2 = System.currentTimeMillis();
- // 4. 0.5s后group1被映射到cluster1下,应该有数据在1s内推送到client端
- assert timestamp2 - timestamp1 < 1500;
-
- // 5. 获取实例
- List<InetSocketAddress> list = registryService.lookup("group1");
- registryService.unsubscribe("group1");
- assertEquals(list.size(), 1);
- InetSocketAddress inetSocketAddress = list.get(0);
- assertEquals(inetSocketAddress.getAddress().getHostAddress(), "127.0.0.1");
- assertEquals(inetSocketAddress.getPort(), 8088);
- }
-
@Disabled
- @Test
- public void testSubscribe() throws Exception {
- NamingserverRegistryServiceImpl registryService = NamingserverRegistryServiceImpl.getInstance();
-
- AtomicBoolean isNotified = new AtomicBoolean(false);
- // 1.subscribe
- registryService.subscribe(
- vGroup -> {
- try {
- isNotified.set(true);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- },
- "group2");
-
- // 2.register
- InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8088);
- registryService.register(inetSocketAddress);
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group2", "cluster1");
-
- // 3.check
- assertEquals(isNotified.get(), true);
- registryService.unsubscribe("group2");
+ public void testWatch() throws Exception {
+ // 1. registering an instance
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress("127.0.0.1", 8888));
+ registryService.register(serviceInstance);
+ Thread.sleep(1000);
+
+ // 2. test for no changes: should return 304
+ boolean result1 = registryService.watch("group1");
+ assertFalse(result1);
+
+ // 3. triggering data changes: Re-registering instances
+ registryService.unregister(serviceInstance);
+ Thread.sleep(1000);
+
+ // set a new term value
+ Instance instance = Instance.getInstance();
+ instance.setTerm(System.currentTimeMillis());
+ registryService.register(serviceInstance);
+ Thread.sleep(1000);
+
+ // 4. test for changes: simulate the client using the old term, and return 200
+ Field termField = NamingserverRegistryServiceImpl.class.getDeclaredField("term");
+ termField.setAccessible(true);
+ termField.set(registryService, 0L);
+
+ boolean result2 = registryService.watch("group1");
+ assertTrue(result2);
+
+ reflectUnsubscribe("group1");
}
@Test
- @Disabled
public void testUnsubscribe() throws Exception {
- NamingserverRegistryServiceImpl registryService =
- (NamingserverRegistryServiceImpl) new NamingserverRegistryProvider().provide();
-
NamingListenerimpl namingListenerimpl = new NamingListenerimpl();
- // 1.subscribe
- registryService.subscribe(namingListenerimpl, "group1");
+ registryService.subscribe(namingListenerimpl, "group3");
- // 2.register
- InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 8088);
- registryService.register(inetSocketAddress);
- String namespace = FILE_CONFIG.getConfig("registry.namingserver.namespace");
- createGroupInCluster(namespace, "group1", "cluster1");
+ registryService.unsubscribe(namingListenerimpl, "group3");
- // 3.check
- assertEquals(namingListenerimpl.isNotified, true);
- namingListenerimpl.setNotified(false);
+ Thread.sleep(2000);
- // 4.unsubscribe
- registryService.unsubscribe(namingListenerimpl, "group1");
+ assertEquals(namingListenerimpl.isNotified, false);
+ }
- // 5.unregister
+ @Test
+ public void testAliveLookup() {
+ String transactionServiceGroup = "test-group";
- registryService.unregister(inetSocketAddress);
- // 5.check
- assertEquals(namingListenerimpl.isNotified, false);
+ List<ServiceInstance> result = registryService.aliveLookup(transactionServiceGroup);
+ assertEquals(0, result.size());
}
- public void createGroupInCluster(String namespace, String vGroup, String clusterName) throws Exception {
- Map<String, String> paraMap = new HashMap<>();
- paraMap.put("namespace", namespace);
- paraMap.put("vGroup", vGroup);
- paraMap.put("clusterName", clusterName);
- String url = "http://127.0.0.1:8080/naming/v1/createGroup";
- Map<String, String> header = new HashMap<>();
- header.put(HTTP.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
- try {
- CloseableHttpResponse response = HttpClientUtil.doGet(url, paraMap, header, 30000);
- } catch (Exception e) {
- throw new RemoteException();
- }
+ private void reflectUnsubscribe(String vGroup) throws Exception {
+ Field listenerServiceMapField = NamingserverRegistryServiceImpl.class.getDeclaredField("LISTENER_SERVICE_MAP");
+ listenerServiceMapField.setAccessible(true);
+ ConcurrentMap<String, List<NamingListener>> listenerServiceMap =
+ (ConcurrentMap<String, List<NamingListener>>) listenerServiceMapField.get(null);
+ listenerServiceMap.remove(vGroup);
}
- private class NamingListenerimpl implements NamingListener {
+ private static class NamingListenerimpl implements NamingListener {
public boolean isNotified = false;
@@ -385,4 +241,3 @@ class NamingserverRegistryServiceImplTest {
}
}
}
-;
diff --git a/discovery/seata-discovery-namingserver/src/test/resources/registry.conf b/discovery/seata-discovery-namingserver/src/test/resources/registry.conf
index 274688f4bb..143e43c1b9 100644
--- a/discovery/seata-discovery-namingserver/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-namingserver/src/test/resources/registry.conf
@@ -17,58 +17,12 @@
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa、custom
- type = "namingserver"
+ type = "seata"
- nacos {
- application = "seata-server"
- serverAddr = "127.0.0.1:8848"
- group = "SEATA_GROUP"
- namespace = ""
- username = ""
- password = ""
- contextPath = "/foo"
- ##if use MSE Nacos with auth, mutex with username/password attribute
- #accessKey = ""
- #secretKey = ""
- ##if use Nacos naming meta-data for SLB service registry, specify nacos address pattern rules here
- #slbPattern = ""
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- password = ""
- timeout = "0"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- username = ""
- password = ""
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- aclToken = ""
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
- file {
- name = "file.conf"
- }
- custom {
- name = ""
+ seata {
+ username = "seata"
+ password = "seata"
+ server-addr = "127.0.0.1:8081"
}
}
@@ -76,45 +30,7 @@ config {
# file、nacos 、apollo、zk、consul、etcd3、springCloudConfig、custom
type = "file"
- nacos {
- serverAddr = "127.0.0.1:8848"
- namespace = ""
- group = "SEATA_GROUP"
- username = ""
- password = ""
- contextPath = "/bar"
- ##if use MSE Nacos with auth, mutex with username/password attribute
- #accessKey = ""
- #secretKey = ""
- dataId = "seata.properties"
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- key = "seata.properties"
- aclToken = ""
- }
- apollo {
- appId = "seata-server"
- apolloMeta = "http://192.168.1.204:8801"
- namespace = "application"
- apolloAccesskeySecret = ""
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- username = ""
- password = ""
- nodePath = "/seata/seata.properties"
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- key = "seata.properties"
- }
file {
name = "file.conf"
}
- custom {
- name = ""
- }
}
diff --git a/discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java b/discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java
index ded156e6c6..2a1dd4f0dd 100644
--- a/discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java
+++ b/discovery/seata-discovery-raft/src/main/java/org/apache/seata/discovery/registry/raft/RaftRegistryServiceImpl.java
@@ -33,6 +33,7 @@ import org.apache.seata.common.exception.RetryableException;
import org.apache.seata.common.metadata.Metadata;
import org.apache.seata.common.metadata.MetadataResponse;
import org.apache.seata.common.metadata.Node;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.HttpClientUtil;
@@ -67,7 +68,6 @@ import java.util.stream.Stream;
/**
* The type File registry service.
- *
*/
public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeListener> {
@@ -103,7 +103,7 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
private static final String IP_PORT_SPLIT_CHAR = ":";
- private static final Map<String, List<InetSocketAddress>> INIT_ADDRESSES = new HashMap<>();
+ private static final Map<String, List<ServiceInstance>> INIT_ADDRESSES = new HashMap<>();
private static final Metadata METADATA = new Metadata();
@@ -120,7 +120,7 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
/**
* Service node health check
*/
- private static final Map<String, List<InetSocketAddress>> ALIVE_NODES = new ConcurrentHashMap<>();
+ private static final Map<String, List<ServiceInstance>> ALIVE_NODES = new ConcurrentHashMap<>();
private static final String PREFERRED_NETWORKS;
@@ -150,10 +150,10 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
}
@Override
- public void register(InetSocketAddress address) throws Exception {}
+ public void register(ServiceInstance address) throws Exception {}
@Override
- public void unregister(InetSocketAddress address) throws Exception {}
+ public void unregister(ServiceInstance address) throws Exception {}
@Override
public void subscribe(String cluster, ConfigChangeListener listener) throws Exception {}
@@ -224,15 +224,15 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
private static String queryHttpAddress(String clusterName, String group) {
List<Node> nodeList = METADATA.getNodes(clusterName, group);
List<String> addressList = null;
- Stream<InetSocketAddress> stream = null;
+ Stream<ServiceInstance> stream = null;
if (CollectionUtils.isNotEmpty(nodeList)) {
- List<InetSocketAddress> inetSocketAddresses = ALIVE_NODES.get(CURRENT_TRANSACTION_SERVICE_GROUP);
- if (CollectionUtils.isEmpty(inetSocketAddresses)) {
+ List<ServiceInstance> serviceInstances = ALIVE_NODES.get(CURRENT_TRANSACTION_SERVICE_GROUP);
+ if (CollectionUtils.isEmpty(serviceInstances)) {
addressList = nodeList.stream()
.map(RaftRegistryServiceImpl::selectControlEndpointStr)
.collect(Collectors.toList());
} else {
- stream = inetSocketAddresses.stream();
+ stream = serviceInstances.stream();
}
} else {
stream = INIT_ADDRESSES.get(clusterName).stream();
@@ -247,16 +247,20 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
map.put(inetSocketAddress.getHostString() + IP_PORT_SPLIT_CHAR + inetSocketAddress.getPort(), node);
}
}
- addressList = stream.map(inetSocketAddress -> {
- String host = NetUtil.toStringHost(inetSocketAddress);
- Node node = map.get(host + IP_PORT_SPLIT_CHAR + inetSocketAddress.getPort());
+ addressList = stream.map(instance -> {
+ String host = NetUtil.toStringHost(instance.getAddress());
+ Node node = map.get(host
+ + IP_PORT_SPLIT_CHAR
+ + instance.getAddress().getPort());
InetSocketAddress controlEndpoint = null;
if (node != null) {
controlEndpoint = selectControlEndpoint(node);
}
return host
+ IP_PORT_SPLIT_CHAR
- + (controlEndpoint != null ? controlEndpoint.getPort() : inetSocketAddress.getPort());
+ + (controlEndpoint != null
+ ? controlEndpoint.getPort()
+ : instance.getAddress().getPort());
})
.collect(Collectors.toList());
return addressList.get(ThreadLocalRandom.current().nextInt(addressList.size()));
@@ -399,12 +403,13 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
}
@Override
- public List<InetSocketAddress> aliveLookup(String transactionServiceGroup) {
+ public List<ServiceInstance> aliveLookup(String transactionServiceGroup) {
if (METADATA.isRaftMode()) {
String clusterName = getServiceGroup(transactionServiceGroup);
Node leader = METADATA.getLeader(clusterName);
if (leader != null) {
- return Collections.singletonList(selectTransactionEndpoint(leader));
+ return ServiceInstance.convertToServiceInstanceSet(
+ Collections.singletonList(selectTransactionEndpoint(leader)));
}
}
return RegistryService.super.aliveLookup(transactionServiceGroup);
@@ -449,21 +454,22 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
}
@Override
- public List<InetSocketAddress> refreshAliveLookup(
- String transactionServiceGroup, List<InetSocketAddress> aliveAddress) {
+ public List<ServiceInstance> refreshAliveLookup(
+ String transactionServiceGroup, List<ServiceInstance> aliveInstances) {
if (METADATA.isRaftMode()) {
Node leader = METADATA.getLeader(getServiceGroup(transactionServiceGroup));
InetSocketAddress leaderAddress = selectTransactionEndpoint(leader);
return ALIVE_NODES.put(
transactionServiceGroup,
- aliveAddress.isEmpty()
- ? aliveAddress
- : aliveAddress.parallelStream()
- .filter(inetSocketAddress -> {
+ aliveInstances.isEmpty()
+ ? aliveInstances
+ : aliveInstances.parallelStream()
+ .filter(serviceInstance -> {
// Since only follower will turn into leader, only the follower node needs to be
// listened to
- return inetSocketAddress.getPort() != leaderAddress.getPort()
- || !inetSocketAddress
+ return serviceInstance.getAddress().getPort() != leaderAddress.getPort()
+ || !serviceInstance
+ .getAddress()
.getAddress()
.getHostAddress()
.equals(leaderAddress
@@ -472,7 +478,7 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
})
.collect(Collectors.toList()));
} else {
- return RegistryService.super.refreshAliveLookup(transactionServiceGroup, aliveAddress);
+ return RegistryService.super.refreshAliveLookup(transactionServiceGroup, aliveInstances);
}
}
@@ -570,7 +576,7 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
String clusterName = getServiceGroup(key);
if (clusterName == null) {
return null;
@@ -580,13 +586,13 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
if (!METADATA.containsGroup(clusterName)) {
String raftClusterAddress = CONFIG.getConfig(getRaftAddrFileKey());
if (StringUtils.isNotBlank(raftClusterAddress)) {
- List<InetSocketAddress> list = new ArrayList<>();
+ List<ServiceInstance> list = new ArrayList<>();
String[] addresses = raftClusterAddress.split(",");
for (String address : addresses) {
String[] endpoint = address.split(IP_PORT_SPLIT_CHAR);
String host = endpoint[0];
int port = Integer.parseInt(endpoint[1]);
- list.add(new InetSocketAddress(host, port));
+ list.add(new ServiceInstance(new InetSocketAddress(host, port)));
}
if (CollectionUtils.isEmpty(list)) {
return null;
@@ -605,9 +611,9 @@ public class RaftRegistryServiceImpl implements RegistryService<ConfigChangeList
}
List<Node> nodes = METADATA.getNodes(clusterName);
if (CollectionUtils.isNotEmpty(nodes)) {
- return nodes.parallelStream()
+ return ServiceInstance.convertToServiceInstanceSet(nodes.parallelStream()
.map(RaftRegistryServiceImpl::selectTransactionEndpoint)
- .collect(Collectors.toList());
+ .collect(Collectors.toList()));
}
return Collections.emptyList();
}
diff --git a/discovery/seata-discovery-raft/src/test/resources/registry.conf b/discovery/seata-discovery-raft/src/test/resources/registry.conf
index 5a15b8eec3..ed256c394e 100644
--- a/discovery/seata-discovery-raft/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-raft/src/test/resources/registry.conf
@@ -18,6 +18,7 @@
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa、custom、raft
type = "raft"
+
raft {
metadata-max-age-ms = 30000
serverAddr = "127.0.0.1:8848"
@@ -30,14 +31,8 @@ registry {
config {
# file、nacos 、apollo、zk、consul、etcd3、springCloudConfig、custom
type = "file"
- raft {
- metadata-max-age-ms = 30000
- serverAddr = "127.0.0.1:8848"
- }
+
file {
name = "file.conf"
}
- custom {
- name = ""
- }
}
diff --git a/discovery/seata-discovery-redis/src/main/java/org/apache/seata/discovery/registry/redis/RedisRegistryServiceImpl.java b/discovery/seata-discovery-redis/src/main/java/org/apache/seata/discovery/registry/redis/RedisRegistryServiceImpl.java
index 80186fcb71..9fd93b2e06 100644
--- a/discovery/seata-discovery-redis/src/main/java/org/apache/seata/discovery/registry/redis/RedisRegistryServiceImpl.java
+++ b/discovery/seata-discovery-redis/src/main/java/org/apache/seata/discovery/registry/redis/RedisRegistryServiceImpl.java
@@ -19,6 +19,7 @@ package org.apache.seata.discovery.registry.redis;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.seata.common.ConfigurationKeys;
import org.apache.seata.common.exception.ShouldNeverHappenException;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.thread.NamedThreadFactory;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
@@ -65,7 +66,7 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
private static final String REDIS_DB = "db";
private static final String REDIS_PASSWORD = "password";
private static final ConcurrentMap<String, List<RedisListener>> LISTENER_SERVICE_MAP = new ConcurrentHashMap<>();
- private static final ConcurrentMap<String, Set<InetSocketAddress>> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<String, Set<ServiceInstance>> CLUSTER_INSTANCE_MAP = new ConcurrentHashMap<>();
private static volatile RedisRegistryServiceImpl instance;
private static volatile JedisPool jedisPool;
@@ -151,7 +152,8 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
}
@Override
- public void register(InetSocketAddress address) {
+ public void register(ServiceInstance instance) {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
doRegisterOrExpire(address, true);
RegistryHeartBeats.addHeartBeat(REGISTRY_TYPE, address, KEY_REFRESH_PERIOD, this::doRegisterOrExpire);
@@ -175,7 +177,8 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
}
@Override
- public void unregister(InetSocketAddress address) {
+ public void unregister(ServiceInstance instance) {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
String serverAddr = NetUtil.toStringAddress(address);
try (Jedis jedis = jedisPool.getResource();
@@ -226,7 +229,7 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
public void unsubscribe(String cluster, RedisListener listener) {}
@Override
- public List<InetSocketAddress> lookup(String key) {
+ public List<ServiceInstance> lookup(String key) {
transactionServiceGroup = key;
String clusterName = getServiceGroup(key);
if (clusterName == null) {
@@ -237,7 +240,7 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
}
// default visible for test
- List<InetSocketAddress> lookupByCluster(String clusterName) {
+ List<ServiceInstance> lookupByCluster(String clusterName) {
if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) {
String redisRegistryKey = REDIS_FILEKEY_PREFIX + clusterName;
try (Jedis jedis = jedisPool.getResource()) {
@@ -250,8 +253,8 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
switch (eventType) {
case RedisListener.REGISTER:
CollectionUtils.computeIfAbsent(
- CLUSTER_ADDRESS_MAP, clusterName, value -> ConcurrentHashMap.newKeySet(2))
- .add(NetUtil.toInetSocketAddress(serverAddr));
+ CLUSTER_INSTANCE_MAP, clusterName, value -> ConcurrentHashMap.newKeySet(2))
+ .add(new ServiceInstance(NetUtil.toInetSocketAddress(serverAddr)));
break;
case RedisListener.UN_REGISTER:
removeServerAddressByPushEmptyProtection(clusterName, serverAddr);
@@ -262,7 +265,7 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
});
}
return new ArrayList<>(CollectionUtils.computeIfAbsent(
- CLUSTER_ADDRESS_MAP, clusterName, value -> ConcurrentHashMap.newKeySet(2)));
+ CLUSTER_INSTANCE_MAP, clusterName, value -> ConcurrentHashMap.newKeySet(2)));
}
/**
@@ -275,10 +278,10 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
*/
private void removeServerAddressByPushEmptyProtection(String notifyCluserName, String serverAddr) {
- Set<InetSocketAddress> socketAddresses = CollectionUtils.computeIfAbsent(
- CLUSTER_ADDRESS_MAP, notifyCluserName, value -> ConcurrentHashMap.newKeySet(2));
- InetSocketAddress inetSocketAddress = NetUtil.toInetSocketAddress(serverAddr);
- if (socketAddresses.size() == 1 && socketAddresses.contains(inetSocketAddress)) {
+ Set<ServiceInstance> serviceInstances = CollectionUtils.computeIfAbsent(
+ CLUSTER_INSTANCE_MAP, notifyCluserName, value -> ConcurrentHashMap.newKeySet(2));
+ ServiceInstance serviceInstance = new ServiceInstance(NetUtil.toInetSocketAddress(serverAddr));
+ if (serviceInstances.size() == 1 && serviceInstances.contains(serviceInstance)) {
String txServiceGroupName =
ConfigurationFactory.getInstance().getConfig(ConfigurationKeys.TX_SERVICE_GROUP);
@@ -289,9 +292,9 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
}
}
}
- socketAddresses.remove(inetSocketAddress);
+ serviceInstances.remove(serviceInstance);
- removeOfflineAddressesIfNecessary(transactionServiceGroup, notifyCluserName, socketAddresses);
+ removeOfflineAddressesIfNecessary(transactionServiceGroup, notifyCluserName, serviceInstances);
}
@Override
@@ -380,8 +383,11 @@ public class RedisRegistryServiceImpl implements RegistryService<RedisListener>
}
} while (!cursor.equals(ScanParams.SCAN_POINTER_START));
- if (CollectionUtils.isNotEmpty(newAddressSet) && !newAddressSet.equals(CLUSTER_ADDRESS_MAP.get(clusterName))) {
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressSet);
+ Set<ServiceInstance> currentInstances = ServiceInstance.convertToServiceInstanceSet(newAddressSet);
+
+ if (CollectionUtils.isNotEmpty(currentInstances)
+ && !currentInstances.equals(CLUSTER_INSTANCE_MAP.get(clusterName))) {
+ CLUSTER_INSTANCE_MAP.put(clusterName, currentInstances);
}
}
diff --git a/discovery/seata-discovery-redis/src/test/java/org/apache/seata/discovery/registry/redis/RedisRegisterServiceImplTest.java b/discovery/seata-discovery-redis/src/test/java/org/apache/seata/discovery/registry/redis/RedisRegisterServiceImplTest.java
index b7de1ca66d..d8738f2d55 100644
--- a/discovery/seata-discovery-redis/src/test/java/org/apache/seata/discovery/registry/redis/RedisRegisterServiceImplTest.java
+++ b/discovery/seata-discovery-redis/src/test/java/org/apache/seata/discovery/registry/redis/RedisRegisterServiceImplTest.java
@@ -16,6 +16,7 @@
*/
package org.apache.seata.discovery.registry.redis;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
@@ -66,12 +67,12 @@ public class RedisRegisterServiceImplTest {
@Test
@Order(1)
public void testFlow() {
-
- redisRegistryService.register(new InetSocketAddress(NetUtil.getLocalIp(), 8091));
+ ServiceInstance serviceInstance = new ServiceInstance(new InetSocketAddress(NetUtil.getLocalIp(), 8091));
+ redisRegistryService.register(serviceInstance);
Assertions.assertTrue(redisRegistryService.lookup("default_tx_group").size() > 0);
- redisRegistryService.unregister(new InetSocketAddress(NetUtil.getLocalIp(), 8091));
+ redisRegistryService.unregister(serviceInstance);
Assertions.assertTrue(redisRegistryService.lookup("default_tx_group").size() > 0);
}
@@ -80,19 +81,19 @@ public class RedisRegisterServiceImplTest {
@Order(2)
public void testRemoveServerAddressByPushEmptyProtection()
throws NoSuchFieldException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
-
MockedStatic<ConfigurationFactory> configurationFactoryMockedStatic = mockStatic(ConfigurationFactory.class);
Configuration configuration = mock(Configuration.class);
when(configuration.getConfig(anyString())).thenReturn("cluster");
configurationFactoryMockedStatic.when(ConfigurationFactory::getInstance).thenReturn(configuration);
- Field field = RedisRegistryServiceImpl.class.getDeclaredField("CLUSTER_ADDRESS_MAP");
+ Field field = RedisRegistryServiceImpl.class.getDeclaredField("CLUSTER_INSTANCE_MAP");
field.setAccessible(true);
- ConcurrentMap<String, Set<InetSocketAddress>> CLUSTER_ADDRESS_MAP =
- (ConcurrentMap<String, Set<InetSocketAddress>>) field.get(null);
- CLUSTER_ADDRESS_MAP.put("cluster", Sets.newSet(NetUtil.toInetSocketAddress("127.0.0.1:8091")));
+ ConcurrentMap<String, Set<ServiceInstance>> CLUSTER_INSTANCE_MAP =
+ (ConcurrentMap<String, Set<ServiceInstance>>) field.get(null);
+ CLUSTER_INSTANCE_MAP.put(
+ "cluster", Sets.newSet(new ServiceInstance(NetUtil.toInetSocketAddress("127.0.0.1:8091"))));
Method method = RedisRegistryServiceImpl.class.getDeclaredMethod(
"removeServerAddressByPushEmptyProtection", String.class, String.class);
@@ -100,7 +101,7 @@ public class RedisRegisterServiceImplTest {
method.invoke(redisRegistryService, "cluster", "127.0.0.1:8091");
// test the push empty protection situation
- Assertions.assertEquals(1, CLUSTER_ADDRESS_MAP.get("cluster").size());
+ Assertions.assertEquals(1, CLUSTER_INSTANCE_MAP.get("cluster").size());
when(configuration.getConfig(anyString())).thenReturn("mycluster");
@@ -108,7 +109,7 @@ public class RedisRegisterServiceImplTest {
configurationFactoryMockedStatic.close();
// test the normal remove situation
- Assertions.assertEquals(0, CLUSTER_ADDRESS_MAP.get("cluster").size());
+ Assertions.assertEquals(0, CLUSTER_INSTANCE_MAP.get("cluster").size());
}
@Test
diff --git a/discovery/seata-discovery-sofa/src/main/java/org/apache/seata/discovery/registry/sofa/SofaRegistryServiceImpl.java b/discovery/seata-discovery-sofa/src/main/java/org/apache/seata/discovery/registry/sofa/SofaRegistryServiceImpl.java
index 0d25de7307..989b84183f 100644
--- a/discovery/seata-discovery-sofa/src/main/java/org/apache/seata/discovery/registry/sofa/SofaRegistryServiceImpl.java
+++ b/discovery/seata-discovery-sofa/src/main/java/org/apache/seata/discovery/registry/sofa/SofaRegistryServiceImpl.java
@@ -26,6 +26,7 @@ import com.alipay.sofa.registry.client.provider.DefaultRegistryClient;
import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder;
import com.alipay.sofa.registry.core.model.ScopeEnum;
import org.apache.commons.lang.StringUtils;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.config.Configuration;
import org.apache.seata.config.ConfigurationFactory;
@@ -74,7 +75,7 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
private static final ConcurrentMap<String, List<SubscriberDataObserver>> LISTENER_SERVICE_MAP =
new ConcurrentHashMap<>();
- private static final ConcurrentMap<String, List<InetSocketAddress>> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<String, List<ServiceInstance>> CLUSTER_INSTANCE_MAP = new ConcurrentHashMap<>();
private static Properties registryProps;
private static volatile RegistryClient registryClient;
@@ -102,7 +103,8 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
String clusterName = registryProps.getProperty(PRO_CLUSTER_KEY);
PublisherRegistration publisherRegistration = new PublisherRegistration(clusterName);
@@ -112,8 +114,8 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
- NetUtil.validAddress(address);
+ public void unregister(ServiceInstance instance) {
+ NetUtil.validAddress(instance.getAddress());
String clusterName = registryProps.getProperty(PRO_CLUSTER_KEY);
getRegistryInstance().unregister(clusterName, registryProps.getProperty(PRO_GROUP_KEY), RegistryType.PUBLISHER);
}
@@ -143,7 +145,7 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
}
@Override
- public void subscribe(String cluster, SubscriberDataObserver listener) throws Exception {
+ public void subscribe(String cluster, SubscriberDataObserver listener) {
SubscriberRegistration subscriberRegistration = new SubscriberRegistration(cluster, listener);
subscriberRegistration.setScopeEnum(ScopeEnum.global);
subscriberRegistration.setGroup(registryProps.getProperty(PRO_GROUP_KEY));
@@ -153,12 +155,12 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
}
@Override
- public void unsubscribe(String cluster, SubscriberDataObserver listener) throws Exception {
+ public void unsubscribe(String cluster, SubscriberDataObserver listener) {
getRegistryInstance().unregister(cluster, registryProps.getProperty(PRO_GROUP_KEY), RegistryType.SUBSCRIBER);
}
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
transactionServiceGroup = key;
String clusterName = getServiceGroup(key);
if (clusterName == null) {
@@ -169,13 +171,13 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
CountDownLatch respondRegistries = new CountDownLatch(1);
subscribe(clusterName, (dataId, data) -> {
Map<String, List<String>> instances = data.getZoneData();
- if (instances == null && CLUSTER_ADDRESS_MAP.get(clusterName) != null) {
- CLUSTER_ADDRESS_MAP.remove(clusterName);
+ if (instances == null && CLUSTER_INSTANCE_MAP.get(clusterName) != null) {
+ CLUSTER_INSTANCE_MAP.remove(clusterName);
} else {
- List<InetSocketAddress> newAddressList = flatData(instances);
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ List<ServiceInstance> newInstanceList = flatData(instances);
+ CLUSTER_INSTANCE_MAP.put(clusterName, newInstanceList);
- removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newAddressList);
+ removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newInstanceList);
}
respondRegistries.countDown();
});
@@ -184,18 +186,18 @@ public class SofaRegistryServiceImpl implements RegistryService<SubscriberDataOb
final String property = registryProps.getProperty(PRO_ADDRESS_WAIT_TIME_KEY);
respondRegistries.await(Integer.parseInt(property), TimeUnit.MILLISECONDS);
}
- return CLUSTER_ADDRESS_MAP.get(clusterName);
+ return CLUSTER_INSTANCE_MAP.get(clusterName);
}
- private List<InetSocketAddress> flatData(Map<String, List<String>> instances) {
- List<InetSocketAddress> result = new ArrayList<>();
+ private List<ServiceInstance> flatData(Map<String, List<String>> instances) {
+ List<ServiceInstance> result = new ArrayList<>();
for (Map.Entry<String, List<String>> entry : instances.entrySet()) {
for (String str : entry.getValue()) {
String ip = StringUtils.substringBeforeLast(str, HOST_SEPERATOR);
String port = StringUtils.substringAfterLast(str, HOST_SEPERATOR);
InetSocketAddress inetSocketAddress = new InetSocketAddress(ip, Integer.parseInt(port));
- result.add(inetSocketAddress);
+ result.add(new ServiceInstance(inetSocketAddress));
}
}
return result;
diff --git a/discovery/seata-discovery-zk/src/main/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImpl.java b/discovery/seata-discovery-zk/src/main/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImpl.java
index 8680a4513e..eaffdf85f4 100644
--- a/discovery/seata-discovery-zk/src/main/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImpl.java
+++ b/discovery/seata-discovery-zk/src/main/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImpl.java
@@ -27,6 +27,7 @@ import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.RetryNTimes;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.CollectionUtils;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.common.util.StringUtils;
@@ -81,7 +82,7 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
ZK_PATH_SPLIT_CHAR + FILE_ROOT_REGISTRY + ZK_PATH_SPLIT_CHAR + REGISTRY_TYPE + ZK_PATH_SPLIT_CHAR;
private static final String ROOT_PATH_WITHOUT_SUFFIX =
ZK_PATH_SPLIT_CHAR + FILE_ROOT_REGISTRY + ZK_PATH_SPLIT_CHAR + REGISTRY_TYPE;
- private static final ConcurrentMap<String, List<InetSocketAddress>> CLUSTER_ADDRESS_MAP = new ConcurrentHashMap<>();
+ private static final ConcurrentMap<String, List<ServiceInstance>> CLUSTER_INSTANCE_MAP = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, List<CuratorCacheListener>> LISTENER_SERVICE_MAP =
new ConcurrentHashMap<>();
private static final ConcurrentMap<String, Object> CLUSTER_LOCK = new ConcurrentHashMap<>();
@@ -107,7 +108,8 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
}
@Override
- public void register(InetSocketAddress address) throws Exception {
+ public void register(ServiceInstance instance) throws Exception {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
String path = getRegisterPathByPath(address);
@@ -145,7 +147,8 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
}
@Override
- public void unregister(InetSocketAddress address) throws Exception {
+ public void unregister(ServiceInstance instance) {
+ InetSocketAddress address = instance.getAddress();
NetUtil.validAddress(address);
String path = getRegisterPathByPath(address);
@@ -154,7 +157,7 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
}
@Override
- public void subscribe(String cluster, CuratorCacheListener listener) throws Exception {
+ public void subscribe(String cluster, CuratorCacheListener listener) {
if (cluster == null) {
return;
}
@@ -185,7 +188,7 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
}
@Override
- public void unsubscribe(String cluster, CuratorCacheListener listener) throws Exception {
+ public void unsubscribe(String cluster, CuratorCacheListener listener) {
if (cluster == null) {
return;
}
@@ -208,7 +211,7 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
* @throws Exception the exception
*/
@Override
- public List<InetSocketAddress> lookup(String key) throws Exception {
+ public List<ServiceInstance> lookup(String key) throws Exception {
transactionServiceGroup = key;
String clusterName = getServiceGroup(key);
@@ -221,7 +224,7 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
}
// visible for test.
- List<InetSocketAddress> doLookup(String clusterName) throws Exception {
+ List<ServiceInstance> doLookup(String clusterName) throws Exception {
if (!LISTENER_SERVICE_MAP.containsKey(clusterName)) {
Object lock = CLUSTER_LOCK.putIfAbsent(clusterName, new Object());
if (null == lock) {
@@ -236,13 +239,13 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
List<String> childClusterPath =
getClientInstance().getChildren().forPath(ROOT_PATH + clusterName);
- refreshClusterAddressMap(clusterName, childClusterPath);
+ refreshClusterInstanceMap(clusterName, childClusterPath);
subscribeCluster(clusterName);
}
}
}
- return CLUSTER_ADDRESS_MAP.get(clusterName);
+ return CLUSTER_INSTANCE_MAP.get(clusterName);
}
@Override
@@ -338,10 +341,10 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
List<String> currentChilds =
getClientInstance().getChildren().forPath(path);
if (CollectionUtils.isEmpty(currentChilds)
- && CLUSTER_ADDRESS_MAP.get(cluster) != null) {
- CLUSTER_ADDRESS_MAP.remove(cluster);
+ && CLUSTER_INSTANCE_MAP.get(cluster) != null) {
+ CLUSTER_INSTANCE_MAP.remove(cluster);
} else if (!CollectionUtils.isEmpty(currentChilds)) {
- ZookeeperRegisterServiceImpl.this.refreshClusterAddressMap(cluster, currentChilds);
+ ZookeeperRegisterServiceImpl.this.refreshClusterInstanceMap(cluster, currentChilds);
}
}
})
@@ -350,23 +353,24 @@ public class ZookeeperRegisterServiceImpl implements RegistryService<CuratorCach
subscribe(cluster, listener);
}
- private void refreshClusterAddressMap(String clusterName, List<String> instances) {
- List<InetSocketAddress> newAddressList = new ArrayList<>();
+ private void refreshClusterInstanceMap(String clusterName, List<String> instances) {
+ List<ServiceInstance> newInstanceList = new ArrayList<>();
if (instances == null) {
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ CLUSTER_INSTANCE_MAP.put(clusterName, newInstanceList);
return;
}
for (String path : instances) {
try {
String[] ipAndPort = NetUtil.splitIPPortStr(path);
- newAddressList.add(new InetSocketAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1])));
+ newInstanceList.add(
+ new ServiceInstance(new InetSocketAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1]))));
} catch (Exception e) {
LOGGER.warn("The cluster instance info is error, instance info:{}", path);
}
}
- CLUSTER_ADDRESS_MAP.put(clusterName, newAddressList);
+ CLUSTER_INSTANCE_MAP.put(clusterName, newInstanceList);
- removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newAddressList);
+ removeOfflineAddressesIfNecessary(transactionServiceGroup, clusterName, newInstanceList);
}
private String getClusterName() {
diff --git a/discovery/seata-discovery-zk/src/test/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImplTest.java b/discovery/seata-discovery-zk/src/test/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImplTest.java
index baffb35630..8ccea8ec3c 100644
--- a/discovery/seata-discovery-zk/src/test/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImplTest.java
+++ b/discovery/seata-discovery-zk/src/test/java/org/apache/seata/discovery/registry/zk/ZookeeperRegisterServiceImplTest.java
@@ -20,6 +20,7 @@ import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;
import org.apache.curator.test.TestingServer;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.common.util.NetUtil;
import org.apache.seata.config.exception.ConfigNotFoundException;
import org.apache.zookeeper.CreateMode;
@@ -56,7 +57,7 @@ public class ZookeeperRegisterServiceImplTest {
}
}
- ZookeeperRegisterServiceImpl service = (ZookeeperRegisterServiceImpl) new ZookeeperRegistryProvider().provide();
+ ZookeeperRegisterServiceImpl service = ZookeeperRegisterServiceImpl.getInstance();
@Test
public void getInstance() {
@@ -78,7 +79,7 @@ public class ZookeeperRegisterServiceImplTest {
@Test
public void testAll() throws Exception {
- service.register(new InetSocketAddress(NetUtil.getLocalAddress(), 33333));
+ service.register(new ServiceInstance(new InetSocketAddress(NetUtil.getLocalAddress(), 33333)));
Assertions.assertThrows(ConfigNotFoundException.class, new Executable() {
@Override
@@ -86,7 +87,7 @@ public class ZookeeperRegisterServiceImplTest {
service.lookup("xxx");
}
});
- List<InetSocketAddress> lookup2 = service.doLookup("default");
+ List<ServiceInstance> lookup2 = service.doLookup("default");
Assertions.assertEquals(1, lookup2.size());
final List<String> data = new ArrayList<>();
@@ -120,7 +121,7 @@ public class ZookeeperRegisterServiceImplTest {
service.subscribe("default", listener2);
- service.unregister(new InetSocketAddress(NetUtil.getLocalAddress(), 33333));
+ service.unregister(new ServiceInstance(new InetSocketAddress(NetUtil.getLocalAddress(), 33333)));
latch2.await(1000, TimeUnit.MILLISECONDS);
Assertions.assertEquals(0, data2.size());
@@ -143,22 +144,26 @@ public class ZookeeperRegisterServiceImplTest {
System.setProperty("txServiceGroup", "default_tx_group");
System.setProperty("service.vgroupMapping.default_tx_group", "cluster");
- List<InetSocketAddress> addressList = zookeeperRegisterService.lookup("default_tx_group");
+ List<ServiceInstance> addressList = zookeeperRegisterService.lookup("default_tx_group");
- Assertions.assertEquals(addressList, Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
+ Assertions.assertEquals(
+ addressList, Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
}
@Test
public void testRemoveOfflineAddressesIfNecessaryNoRemoveCase() {
- Map<String, List<InetSocketAddress>> addresses =
- service.CURRENT_ADDRESS_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
- addresses.put("cluster", Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
+ Map<String, List<ServiceInstance>> addresses =
+ service.CURRENT_INSTANCE_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
+ addresses.put(
+ "cluster", Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
service.removeOfflineAddressesIfNecessary(
- "default_tx_group", "cluster", Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
+ "default_tx_group",
+ "cluster",
+ Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
Assertions.assertEquals(
1,
- service.CURRENT_ADDRESS_MAP
+ service.CURRENT_INSTANCE_MAP
.get("default_tx_group")
.get("cluster")
.size());
@@ -166,17 +171,20 @@ public class ZookeeperRegisterServiceImplTest {
@Test
public void testRemovePreventEmptyPushCase() {
- Map<String, List<InetSocketAddress>> addresses =
- service.CURRENT_ADDRESS_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
+ Map<String, List<ServiceInstance>> addresses =
+ service.CURRENT_INSTANCE_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
- addresses.put("cluster", Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
+ addresses.put(
+ "cluster", Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
service.removeOfflineAddressesIfNecessary(
- "default_tx_group", "cluster", Collections.singletonList(new InetSocketAddress("127.0.0.2", 8091)));
+ "default_tx_group",
+ "cluster",
+ Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.2", 8091))));
Assertions.assertEquals(
1,
- service.CURRENT_ADDRESS_MAP
+ service.CURRENT_INSTANCE_MAP
.get("default_tx_group")
.get("cluster")
.size());
@@ -184,16 +192,17 @@ public class ZookeeperRegisterServiceImplTest {
@Test
public void testAliveLookup() {
-
System.setProperty("txServiceGroup", "default_tx_group");
System.setProperty("service.vgroupMapping.default_tx_group", "cluster");
- Map<String, List<InetSocketAddress>> addresses =
- service.CURRENT_ADDRESS_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
- addresses.put("cluster", Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
- List<InetSocketAddress> result = service.aliveLookup("default_tx_group");
+ Map<String, List<ServiceInstance>> addresses =
+ service.CURRENT_INSTANCE_MAP.computeIfAbsent("default_tx_group", k -> new HashMap<>());
+ addresses.put(
+ "cluster", Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
+ List<ServiceInstance> result = service.aliveLookup("default_tx_group");
- Assertions.assertEquals(result, Collections.singletonList(new InetSocketAddress("127.0.0.1", 8091)));
+ Assertions.assertEquals(
+ result, Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.1", 8091))));
}
@Test
@@ -203,10 +212,11 @@ public class ZookeeperRegisterServiceImplTest {
System.setProperty("service.vgroupMapping.default_tx_group", "cluster");
service.refreshAliveLookup(
- "default_tx_group", Collections.singletonList(new InetSocketAddress("127.0.0.2", 8091)));
+ "default_tx_group",
+ Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.2", 8091))));
Assertions.assertEquals(
- service.CURRENT_ADDRESS_MAP.get("default_tx_group").get("cluster"),
- Collections.singletonList(new InetSocketAddress("127.0.0.2", 8091)));
+ service.CURRENT_INSTANCE_MAP.get("default_tx_group").get("cluster"),
+ Collections.singletonList(new ServiceInstance(new InetSocketAddress("127.0.0.2", 8091))));
}
}
diff --git a/discovery/seata-discovery-zk/src/test/resources/registry.conf b/discovery/seata-discovery-zk/src/test/resources/registry.conf
index 8b8a0f5b88..e3f682f642 100644
--- a/discovery/seata-discovery-zk/src/test/resources/registry.conf
+++ b/discovery/seata-discovery-zk/src/test/resources/registry.conf
@@ -19,74 +19,22 @@ registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "file"
- nacos {
- application = "seata-server"
- serverAddr = "localhost"
- namespace = ""
- cluster = "default"
- }
- eureka {
- serviceUrl = "http://localhost:8761/eureka"
- application = "default"
- weight = "1"
- }
- redis {
- serverAddr = "localhost:6379"
- db = "0"
- }
- zk {
- cluster = "default"
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- consul {
- cluster = "default"
- serverAddr = "127.0.0.1:8500"
- }
- etcd3 {
- cluster = "default"
- serverAddr = "http://localhost:2379"
- }
- sofa {
- serverAddr = "127.0.0.1:9603"
- application = "default"
- region = "DEFAULT_ZONE"
- datacenter = "DefaultDataCenter"
- cluster = "default"
- group = "SEATA_GROUP"
- addressWaitTime = "3000"
- }
file {
name = "file.conf"
}
+
+ zk {
+ cluster = "default"
+ serverAddr = "127.0.0.1:2181"
+ sessionTimeout = 6000
+ connectTimeout = 2000
+ }
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
- nacos {
- serverAddr = "localhost"
- namespace = ""
- group = "SEATA_GROUP"
- }
- consul {
- serverAddr = "127.0.0.1:8500"
- }
- apollo {
- appId = "seata-server"
- apolloMeta = "http://192.168.1.204:8801"
- namespace = "application"
- }
- zk {
- serverAddr = "127.0.0.1:2181"
- sessionTimeout = 6000
- connectTimeout = 2000
- }
- etcd3 {
- serverAddr = "http://localhost:2379"
- }
file {
name = "file.conf"
}
diff --git a/server/src/main/java/org/apache/seata/server/cluster/raft/RaftServerManager.java b/server/src/main/java/org/apache/seata/server/cluster/raft/RaftServerManager.java
index bf09e53a4d..acdf6dee2d 100644
--- a/server/src/main/java/org/apache/seata/server/cluster/raft/RaftServerManager.java
+++ b/server/src/main/java/org/apache/seata/server/cluster/raft/RaftServerManager.java
@@ -101,9 +101,9 @@ public class RaftServerManager {
return;
} else {
if (RAFT_MODE) {
- for (RegistryService<?> instance : MultiRegistryFactory.getInstances()) {
- if (!(instance instanceof FileRegistryServiceImpl)
- && !(instance instanceof NamingserverRegistryServiceImpl)) {
+ for (RegistryService<?> registryService : MultiRegistryFactory.getInstances()) {
+ if (!(registryService instanceof FileRegistryServiceImpl)
+ && !(registryService instanceof NamingserverRegistryServiceImpl)) {
throw new IllegalArgumentException("Raft store mode not support other Registration Center");
}
}
diff --git a/server/src/main/java/org/apache/seata/server/storage/raft/store/RaftVGroupMappingStoreManager.java b/server/src/main/java/org/apache/seata/server/storage/raft/store/RaftVGroupMappingStoreManager.java
index 1396ded4a7..e81c6ed242 100644
--- a/server/src/main/java/org/apache/seata/server/storage/raft/store/RaftVGroupMappingStoreManager.java
+++ b/server/src/main/java/org/apache/seata/server/storage/raft/store/RaftVGroupMappingStoreManager.java
@@ -20,6 +20,7 @@ import com.alipay.sofa.jraft.Closure;
import org.apache.seata.common.loader.LoadLevel;
import org.apache.seata.common.metadata.ClusterRole;
import org.apache.seata.common.metadata.Instance;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.core.store.MappingDO;
import org.apache.seata.discovery.registry.MultiRegistryFactory;
import org.apache.seata.discovery.registry.RegistryService;
@@ -29,6 +30,7 @@ import org.apache.seata.server.cluster.raft.sync.msg.RaftVGroupSyncMsg;
import org.apache.seata.server.cluster.raft.util.RaftTaskUtil;
import org.apache.seata.server.store.VGroupMappingStoreManager;
+import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@@ -136,8 +138,11 @@ public class RaftVGroupMappingStoreManager implements VGroupMappingStoreManager
Instance node = instance.clone();
node.setRole(RaftServerManager.isLeader(group) ? ClusterRole.LEADER : ClusterRole.FOLLOWER);
Instance.getInstances().add(node);
+ InetSocketAddress inetSocketAddress = new InetSocketAddress(
+ node.getTransaction().getHost(), node.getTransaction().getPort());
+ ServiceInstance serviceInstance = new ServiceInstance(inetSocketAddress, node.getMetadata());
for (RegistryService<?> registryService : MultiRegistryFactory.getInstances()) {
- registryService.register(node);
+ registryService.register(serviceInstance);
}
}
} catch (Exception e) {
diff --git a/server/src/main/java/org/apache/seata/server/store/VGroupMappingStoreManager.java b/server/src/main/java/org/apache/seata/server/store/VGroupMappingStoreManager.java
index f58a7d11fc..d6241fdd21 100644
--- a/server/src/main/java/org/apache/seata/server/store/VGroupMappingStoreManager.java
+++ b/server/src/main/java/org/apache/seata/server/store/VGroupMappingStoreManager.java
@@ -18,6 +18,7 @@ package org.apache.seata.server.store;
import org.apache.seata.common.XID;
import org.apache.seata.common.metadata.Instance;
+import org.apache.seata.common.metadata.ServiceInstance;
import org.apache.seata.core.store.MappingDO;
import org.apache.seata.discovery.registry.MultiRegistryFactory;
import org.apache.seata.discovery.registry.RegistryService;
@@ -59,9 +60,10 @@ public interface VGroupMappingStoreManager {
Map<String, Object> map = this.readVGroups();
instance.addMetadata("vGroup", map);
try {
- InetSocketAddress address = new InetSocketAddress(XID.getIpAddress(), XID.getPort());
+ ServiceInstance serviceInstance = new ServiceInstance(
+ new InetSocketAddress(XID.getIpAddress(), XID.getPort()), instance.getMetadata());
for (RegistryService<?> registryService : MultiRegistryFactory.getInstances()) {
- registryService.register(address);
+ registryService.register(serviceInstance);
}
} catch (Exception e) {
throw new RuntimeException("vGroup mapping relationship notified failed! ", e);
diff --git a/server/src/main/resources/application.raft.example.yml b/server/src/main/resources/application.raft.example.yml
index 14ce8432fa..d614d5fcbf 100644
--- a/server/src/main/resources/application.raft.example.yml
+++ b/server/src/main/resources/application.raft.example.yml
@@ -82,6 +82,8 @@ seata:
# support: nacos 、 eureka 、 redis 、 zk 、 consul 、 etcd3 、 sofa
type: file
preferred-networks: 30.240.*
+ metadata:
+ weight: 100
seata:
server-addr: 127.0.0.1:8081
cluster: default
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@seata.apache.org
For additional commands, e-mail: notifications-help@seata.apache.org