com.alibaba.nacos.api.naming.pojo.Instance Java Examples

The following examples show how to use com.alibaba.nacos.api.naming.pojo.Instance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceConsumer.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
public static void printInstances(NamingEvent namingEvent) {
    List<Instance> instanceList = namingEvent.getInstances();
    StringBuilder sb = new StringBuilder();
    sb.append("[\n");
    int i = 0, s = instanceList.size();
    for (Instance instance : instanceList) {
        sb.append("\t").append(instance);
        if (i++ < s - 1) {
            sb.append(",").append("\n");
        }
    }
    sb.append("\n]");
    System.out.println("===========receive new service===========\nserviceName=" + namingEvent.getServiceName()
            + "\ninstance size=" + instanceList.size()
            + "\ninstance list=" + sb.toString()
            + "\n=========================================\n");
}
 
Example #2
Source File: NacosRegistryProviderObserver.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Update providers.
 *
 * @param config the config 
 * @param instances the instances
 */
void updateProviders(ConsumerConfig config, List<Instance> instances) {
    if (LOGGER.isInfoEnabled(config.getAppName())) {
        LOGGER.infoWithApp(config.getAppName(),
            "Receive update provider: serviceName={}, size={}, data={}",
            NacosRegistryHelper.buildServiceName(config, config.getProtocol()), instances.size(),
            instances);
    }
    List<ProviderInfoListener> providerInfoListeners = providerListenerMap.get(config);
    if (CommonUtils.isNotEmpty(providerInfoListeners)) {
        List<ProviderInfo> providerInfos = NacosRegistryHelper.convertInstancesToProviders(instances);
        List<ProviderInfo> matchProviders = RegistryUtils.matchProviderInfos(config, providerInfos);

        for (ProviderInfoListener providerInfoListener : providerInfoListeners) {
            providerInfoListener
                .updateAllProviders(Collections.singletonList(new ProviderGroup().addAll(matchProviders)));
        }
    }
}
 
Example #3
Source File: NacosRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static String convertInstanceToUrl(Instance instance) {
    Map<String, String> metaData = instance.getMetadata();
    if (metaData == null) {
        metaData = new HashMap<String, String>();
    }
    String uri = "";
    String protocol = metaData.get(RpcConstants.CONFIG_KEY_PROTOCOL);
    if (StringUtils.isNotEmpty(protocol)) {
        uri = protocol + "://";
    }
    uri += instance.getIp() + ":" + instance.getPort();

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : metaData.entrySet()) {
        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
    }
    if (sb.length() > 0) {
        uri += sb.replace(0, 1, "?").toString();
    }
    return uri;
}
 
Example #4
Source File: NacosServiceDiscovery.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
private InstanceInfo createInstanceInfo(Instance instance) {
    InstanceStatus instanceStatus = InstanceStatus.DOWN;
    if (instance.isEnabled()) {
        if (instance.isHealthy()) {
            instanceStatus = InstanceStatus.UP;
        } else {
            instanceStatus = InstanceStatus.OUT_OF_SERVICE;
        }
    }

    return InstanceInfo.builder()
            .serviceId(instance.getServiceName())
            .instanceId(instance.getInstanceId())
            .host(instance.getIp())
            .port(instance.getPort())
            .instanceStatus(instanceStatus)
            .build();
}
 
Example #5
Source File: NacosSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(TaskDO taskDO) {
    try {

        NamingService sourceNamingService =
            nacosServerHolder.get(taskDO.getSourceClusterId(), taskDO.getGroupName());
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName());

        sourceNamingService.unsubscribe(taskDO.getServiceName(), nacosListenerMap.get(taskDO.getTaskId()));

        // 删除目标集群中同步的实例列表
        List<Instance> instances = destNamingService.getAllInstances(taskDO.getServiceName());
        for (Instance instance : instances) {
            if (needDelete(instance.getMetadata(), taskDO)) {
                destNamingService.deregisterInstance(taskDO.getServiceName(), instance.getIp(), instance.getPort());
            }
        }
    } catch (Exception e) {
        log.error("delete task from nacos to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #6
Source File: ConsulSyncToNacosServiceImplTest.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
public void mockSync(TaskDO taskDO) throws Exception {
    Instance instance = mock(Instance.class);
    Map<String, String> metadata = Maps.newHashMap();
    metadata.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, TEST_SOURCE_CLUSTER_ID);
    HealthService healthServiceUp = buildHealthService(TEST_INSTANCE_ADDRESS, 8080, Maps.newHashMap());
    HealthService healthServiceDown = buildHealthService(TEST_INSTANCE_ADDRESS, 8081, metadata);
    List<HealthService> healthServiceList = Lists.newArrayList(healthServiceUp,healthServiceDown);
    RawResponse rawResponse = new RawResponse(200,null,null,1000L,true,100L);
    Response<List<HealthService>> response = new Response<>(healthServiceList,rawResponse);
    when(taskDO.getTaskId()).thenReturn(TEST_TASK_ID);
    when(taskDO.getSourceClusterId()).thenReturn(TEST_SOURCE_CLUSTER_ID);
    when(taskDO.getDestClusterId()).thenReturn(TEST_DEST_CLUSTER_ID);
    doReturn(destNamingService).when(nacosServerHolder).get(anyString(), any());
    doReturn(consulClient).when(consulServerHolder).get(anyString(), any());
    doReturn(response).when(consulClient).getHealthServices(anyString(),anyBoolean(), any());
    List<Instance> allInstances = Lists.newArrayList(instance);
    doReturn(allInstances).when(destNamingService).getAllInstances(anyString());
    doReturn(ClusterTypeEnum.EUREKA).when(skyWalkerCacheServices).getClusterType(any());

}
 
Example #7
Source File: DubboNacosRegistry.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
@Override
protected URL createShardUrl(String defProtocol, Instance instance) {
    Map<String, String> meta = instance.getMetadata();
    String alias = meta.remove(DUBBO_GROUP_KEY);
    alias = alias == null ? ALIAS_OPTION.getValue() : alias;
    if (!instance.isEnabled() || !url.getString(ALIAS_OPTION).equals(alias)) {
        return null;
    }
    String protocol = meta.remove(DUBBO_PROTOCOL_KEY);
    protocol = protocol == null || protocol.isEmpty() ? defProtocol : protocol;
    String ifaceName = meta.remove(DUBBO_PATH_KEY);
    String serviceVersion = meta.remove(DUBBO_SERVICE_VERSION_KEY);
    //重置alias
    meta.put(ALIAS_OPTION.getName(), alias);
    //重置serviceVersion
    meta.put(SERVICE_VERSION_OPTION.getName(), serviceVersion);
    //创建URL
    return new URL(protocol, instance.getIp(), instance.getPort(), ifaceName, meta);
}
 
Example #8
Source File: NamingServiceNacosImpl.java    From chronus with Apache License 2.0 6 votes vote down vote up
@Override
public void onlineNode(Node node) throws Exception {
    List<String> clusters = new ArrayList<>(1);
    clusters.add(node.getCluster());
    List<Instance> instanceList = nacosNamingService.getAllInstances(ChronusConstants.NODE_NAME_CHRONUS, clusters);
    if (CollectionUtils.isEmpty(instanceList)) {
        return;
    }
    Instance instance = instanceList.stream().filter(e -> InstanceUtils.getAddressByInstance(e).equals(node.getAddress())).findFirst().orElse(null);
    if (instance != null) {
        instance.setEnabled(true);
        instance.getMetadata().put(ChronusConstants.REGISTER_TIME, String.valueOf(System.currentTimeMillis()));
        instance.getMetadata().put(ChronusConstants.DATA_VERSION, String.valueOf(System.currentTimeMillis()));
        namingMaintainService.updateInstance(ChronusConstants.NODE_NAME_CHRONUS, instance);
    }
}
 
Example #9
Source File: NacosServer.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
public NacosServer(final Instance instance) {
	super(instance.getIp(), instance.getPort());
	this.instance = instance;
	this.metaInfo = new MetaInfo() {
		@Override
		public String getAppName() {
			return instance.getServiceName();
		}

		@Override
		public String getServerGroup() {
			return null;
		}

		@Override
		public String getServiceIdForDiscovery() {
			return null;
		}

		@Override
		public String getInstanceId() {
			return instance.getInstanceId();
		}
	};
	this.metadata = instance.getMetadata();
}
 
Example #10
Source File: NacosSyncToZookeeperServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
private void tryToCompensate(TaskDO taskDO, NamingService sourceNamingService, List<Instance> sourceInstances) {
    if (!CollectionUtils.isEmpty(sourceInstances)) {
        final PathChildrenCache pathCache = getPathCache(taskDO);
        if (pathCache.getListenable().size() == 0) { // 防止重复注册
            pathCache.getListenable().addListener((zkClient, zkEvent) -> {
                if (zkEvent.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED) {
                    List<Instance> allInstances =
                        sourceNamingService.getAllInstances(taskDO.getServiceName());
                    for (Instance instance : allInstances) {
                        String instanceUrl = buildSyncInstance(instance, taskDO);
                        String zkInstancePath = zkEvent.getData().getPath();
                        if (zkInstancePath.equals(instanceUrl)) {
                            zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL)
                                .forPath(zkInstancePath);
                            break;
                        }
                    }
                }
            });
        }

    }
}
 
Example #11
Source File: ZookeeperSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(TaskDO taskDO) {
    try {

        CloseableUtils.closeQuietly(pathChildrenCacheMap.get(taskDO.getTaskId()));
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        if (nacosServiceNameMap.containsKey(taskDO.getTaskId())) {
            List<Instance> allInstances =
                destNamingService.getAllInstances(nacosServiceNameMap.get(taskDO.getTaskId()));
            for (Instance instance : allInstances) {
                if (needDelete(instance.getMetadata(), taskDO)) {
                    destNamingService.deregisterInstance(instance.getServiceName(), instance.getIp(),
                        instance.getPort());
                }
                nacosServiceNameMap.remove(taskDO.getTaskId());

            }
        }

    } catch (Exception e) {
        log.error("delete task from zookeeper to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #12
Source File: ServiceConsumer.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
public static void mockConsume(NamingService naming, String serviceName) {
    int i = 0, loop = 5;
    try {
        while (i++ < loop) {
            Instance instance = naming.selectOneHealthyInstance(serviceName);
            if (instance != null) {
                System.out.println("get one healthy instance of service:" + serviceName
                        + "\nip=" + instance.getIp() + ", port=" + instance.getPort()
                        + ", cluster=" + instance.getClusterName()
                        + "\n=========================================\n");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(TaskDO taskDO) {

    try {
        specialSyncEventBus.unsubscribe(taskDO);
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        List<Instance> allInstances = destNamingService.getAllInstances(taskDO.getServiceName());
        for (Instance instance : allInstances) {
            if (needDelete(instance.getMetadata(), taskDO)) {

                destNamingService.deregisterInstance(taskDO.getServiceName(), instance.getIp(), instance.getPort());
            }
        }

    } catch (Exception e) {
        log.error("delete task from consul to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #14
Source File: NamingServiceNacosImpl.java    From chronus with Apache License 2.0 6 votes vote down vote up
@Override
public void registerNode() throws Exception {
    Instance instance = new Instance();
    instance.setInstanceId(currentNode.getAddress());
    instance.setIp(currentNode.getIp());
    instance.setClusterName(currentNode.getCluster());
    instance.setPort(currentNode.getPort());
    Map<String, String> metadata = new HashMap<>();
    metadata.put(ChronusConstants.HOST_NAME, currentNode.getHostName());
    metadata.put(ChronusConstants.REGISTER_TIME, currentNode.getVersion());
    metadata.put(ChronusConstants.CLUSTER, currentNode.getCluster());
    if (Objects.equals(ChronusConstants.Y, currentNode.getEnableMaster())) {
        metadata.put(ChronusConstants.IS_MASTER, ChronusConstants.N);
    }
    metadata.put(ChronusConstants.ENABLE_MASTER, currentNode.getEnableMaster());
    metadata.put(ChronusConstants.ENABLE_EXECUTOR, currentNode.getEnableExecutor());
    metadata.put(ChronusConstants.TAG, ChronusConstants.DEF_TAG);
    metadata.put(ChronusConstants.DATA_VERSION, currentNode.getVersion());
    instance.setMetadata(metadata);
    nacosNamingService.registerInstance(ChronusConstants.NODE_NAME_CHRONUS, instance);
    //https://github.com/nacos-group/nacos-spring-project/issues/144
    //namingMaintainService = NamingMaintainFactory.createMaintainService(environment.getProperty("nacos.discovery.server-addr"));
}
 
Example #15
Source File: NacosServiceRegistry.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private Instance getNacosInstanceFromRegistration(Registration registration) {
	Instance instance = new Instance();
	instance.setIp(registration.getHost());
	instance.setPort(registration.getPort());
	instance.setWeight(nacosDiscoveryProperties.getWeight());
	instance.setClusterName(nacosDiscoveryProperties.getClusterName());
	instance.setEnabled(nacosDiscoveryProperties.isInstanceEnabled());
	instance.setMetadata(registration.getMetadata());

	return instance;
}
 
Example #16
Source File: DubboNacosRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected Instance createInstance(URL url) {
    MapParametric<String, Object> context = new MapParametric(GlobalContext.getContext());
    //metadata
    Map<String, String> meta = new HashMap<>();
    String side = url.getString(ROLE_OPTION);
    meta.put(ROLE_OPTION.getName(), side);
    meta.put(DUBBO_RELEASE_KEY, DUBBO_RELEASE_VALUE);
    meta.put(DUBBO_PROTOCOL_VERSION_KEY, DUBBO_PROTOCOL_VERSION_VALUE);
    meta.put(DUBBO_PID_KEY, context.getString(KEY_PID));
    meta.put(DUBBO_INTERFACE_KEY, url.getPath());
    String serviceVersion = url.getString(SERVICE_VERSION_OPTION);
    if (serviceVersion != null && !serviceVersion.isEmpty()) {
        meta.put(DUBBO_SERVICE_VERSION_KEY, serviceVersion);
        meta.put(DUBBO_SERVICE_REVERSION_KEY, serviceVersion);
    }
    meta.put(DUBBO_GENERIC_KEY, String.valueOf(url.getBoolean(GENERIC_OPTION)));
    meta.put(DUBBO_PATH_KEY, url.getPath());
    meta.put(DUBBO_DEFAULT_KEY, "true");
    meta.put(DUBBO_PROTOCOL_KEY, DUBBO_PROTOCOL_VALUE);
    meta.put(DUBBO_APPLICATION_KEY, context.getString(KEY_APPNAME));
    meta.put(DUBBO_DYNAMIC_KEY, String.valueOf(url.getBoolean(DYNAMIC_OPTION)));
    meta.put(DUBBO_CATEGORY_KEY, SIDE_PROVIDER.equals(side) ? DUBBO_CATEGORY_PROVIDERS : DUBBO_CATEGORY_CONSUMERS);
    meta.put(DUBBO_ANYHOST_KEY, "true");
    meta.put(DUBBO_GROUP_KEY, url.getString(ALIAS_OPTION));
    meta.put(DUBBO_TIMESTAMP_KEY, String.valueOf(SystemClock.now()));
    String tagKey = url.getString(TAG_KEY_OPTION);
    String tag = url.getString(tagKey);
    if (tag != null && !tag.isEmpty()) {
        meta.put(tagKey, tag);
    }
    //创建instace
    Instance instance = new Instance();
    instance.setIp(url.getHost());
    instance.setPort(url.getPort());
    instance.setMetadata(meta);
    return instance;
}
 
Example #17
Source File: NacosRegistry.java    From joyrpc with Apache License 2.0 5 votes vote down vote up
@Override
protected CompletableFuture<Void> doDeregister(Registion registion) {
    NacosRegistion nacosRegistion = (NacosRegistion) registion;
    String serviceName = nacosRegistion.getServiceName();
    Instance instance = nacosRegistion.getInstance();
    return Futures.call(future -> {
        registry.namingService.deregisterInstance(serviceName, instance.getIp(), instance.getPort());
        future.complete(null);
    });
}
 
Example #18
Source File: NacosMockTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public static Instance serviceInstance(String serviceName, boolean isHealthy,
		String host, int port, Map<String, String> metadata) {
	Instance instance = new Instance();
	instance.setIp(host);
	instance.setPort(port);
	instance.setServiceName(serviceName);
	instance.setHealthy(isHealthy);
	instance.setMetadata(metadata);
	return instance;
}
 
Example #19
Source File: NacosServerList.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private List<NacosServer> instancesToServerList(List<Instance> instances) {
	List<NacosServer> result = new ArrayList<>();
	if (CollectionUtils.isEmpty(instances)) {
		return result;
	}
	for (Instance instance : instances) {
		result.add(new NacosServer(instance));
	}

	return result;
}
 
Example #20
Source File: NacosServerListTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testGetServers() throws Exception {

	ArrayList<Instance> instances = new ArrayList<>();
	instances.add(NacosMockTest.serviceInstance("test-service", false,
			Collections.emptyMap()));

	NacosDiscoveryProperties nacosDiscoveryProperties = mock(
			NacosDiscoveryProperties.class);

	NamingService namingService = mock(NamingService.class);

	when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
	when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
	when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
	when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
			.thenReturn(instances);

	IClientConfig clientConfig = mock(IClientConfig.class);
	when(clientConfig.getClientName()).thenReturn("test-service");
	NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
	serverList.initWithNiwsConfig(clientConfig);
	List<NacosServer> servers = serverList.getInitialListOfServers();
	assertThat(servers).hasSize(1);

	servers = serverList.getUpdatedListOfServers();
	assertThat(servers).hasSize(1);
}
 
Example #21
Source File: NacosRegistry.java    From dubbo-registry-nacos with Apache License 2.0 5 votes vote down vote up
private URL buildURL(Instance instance) {
    Map<String, String> metadata = instance.getMetadata();
    String protocol = metadata.get(PROTOCOL_KEY);
    String path = metadata.get(PATH_KEY);
    return new URL(protocol,
            instance.getIp(),
            instance.getPort(),
            path,
            instance.getMetadata());
}
 
Example #22
Source File: NacosRegistryHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Convert provider to instances list.
 *
 * @param providerConfig the provider config 
 * @return the list
 */
static List<Instance> convertProviderToInstances(ProviderConfig providerConfig) {
    @SuppressWarnings("unchecked")
    List<ServerConfig> servers = providerConfig.getServer();
    if (servers != null && !servers.isEmpty()) {
        List<Instance> instances = new ArrayList<Instance>();
        for (ServerConfig server : servers) {
            String serviceName = buildServiceName(providerConfig, server.getProtocol());
            Instance instance = new Instance();
            instance.setClusterName(DEFAULT_CLUSTER);
            instance.setServiceName(serviceName);

            // set host port
            String host = server.getVirtualHost();
            if (host == null) {
                host = server.getHost();
                if (NetUtils.isLocalHost(host) || NetUtils.isAnyHost(host)) {
                    host = SystemInfo.getLocalHost();
                }
            }
            instance.setIp(host);
            instance.setPort(server.getPort());

            // set meta data
            Map<String, String> metaData = RegistryUtils.convertProviderToMap(providerConfig, server);
            instance.setMetadata(metaData);

            instances.add(instance);
        }
        return instances;
    }
    return null;
}
 
Example #23
Source File: NacosServiceDiscovery.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public List<InstanceInfo> listInstanceInfos(String serviceId) {
    List<Instance> instances = null;
    try {
        instances = discoveryProperties.namingServiceInstance().getAllInstances(serviceId, false);
    } catch (NacosException e) {
        log.error(e.getMessage(), e);
        return ListUtils.EMPTY_LIST;
    }
    return instances.stream().map(this::createInstanceInfo).collect(Collectors.toList());
}
 
Example #24
Source File: NacosNamingServiceUtils.java    From dubbo-registry-nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Convert the {@link ServiceInstance} to {@link Instance}
 *
 * @param serviceInstance {@link ServiceInstance}
 * @return non-null
 * @since 2.7.5
 */
public static Instance toInstance(ServiceInstance serviceInstance) {
    Instance instance = new Instance();
    instance.setInstanceId(serviceInstance.getId());
    instance.setServiceName(serviceInstance.getServiceName());
    instance.setIp(serviceInstance.getHost());
    instance.setPort(serviceInstance.getPort());
    instance.setMetadata(serviceInstance.getMetadata());
    instance.setEnabled(serviceInstance.isEnabled());
    instance.setHealthy(serviceInstance.isHealthy());
    return instance;
}
 
Example #25
Source File: NacosSyncToNacosServiceImplTest.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
public void mockDelete(TaskDO taskDO) throws Exception {
    Instance instance = mock(Instance.class);
    when(taskDO.getTaskId()).thenReturn(TEST_TASK_ID);
    when(taskDO.getSourceClusterId()).thenReturn(TEST_SOURCE_CLUSTER_ID);
    when(taskDO.getDestClusterId()).thenReturn(TEST_DEST_CLUSTER_ID);
    doReturn(destNamingService).when(nacosServerHolder).get(anyString(), anyString());
    doReturn(sourceNamingService).when(nacosServerHolder).get(anyString(), anyString());
    doNothing().when(sourceNamingService).unsubscribe(any(), any());
    Map<String, String> metadata = Maps.newHashMap();
    metadata.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, TEST_SOURCE_CLUSTER_ID);
    List<Instance> allInstances = Lists.newArrayList(instance);
    doReturn(allInstances).when(sourceNamingService).getAllInstances(anyString());
    doReturn(metadata).when(instance).getMetadata();
}
 
Example #26
Source File: EurekaSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private void removeInvalidInstance(TaskDO taskDO, NamingService destNamingService,
    List<InstanceInfo> eurekaInstances, List<Instance> nacosInstances) throws NacosException {
    for (Instance instance : nacosInstances) {
        if (!isExistInEurekaInstance(eurekaInstances, instance) && needDelete(instance.getMetadata(), taskDO)) {
            log.info("Remove invalid service instance from Nacos, serviceName={}, Ip={}, port={}",
                instance.getServiceName(), instance.getIp(), instance.getPort());
            destNamingService.deregisterInstance(taskDO.getServiceName(), instance.getIp(), instance.getPort());
        }
    }
}
 
Example #27
Source File: NacosMockTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public static Instance serviceInstance(String serviceName, boolean isHealthy,
		Map<String, String> metadata) {
	Instance instance = new Instance();
	instance.setInstanceId(UUID.randomUUID().toString());
	instance.setServiceName(serviceName);
	instance.setHealthy(isHealthy);
	instance.setMetadata(metadata);
	return instance;
}
 
Example #28
Source File: EurekaSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private Instance buildSyncInstance(InstanceInfo instance, TaskDO taskDO) {
    Instance temp = new Instance();
    temp.setIp(instance.getIPAddr());
    temp.setPort(instance.getPort());
    temp.setServiceName(instance.getAppName());
    temp.setHealthy(true);

    Map<String, String> metaData = new HashMap<>(instance.getMetadata());
    metaData.put(SkyWalkerConstants.DEST_CLUSTERID_KEY, taskDO.getDestClusterId());
    metaData.put(SkyWalkerConstants.SYNC_SOURCE_KEY,
        skyWalkerCacheServices.getClusterType(taskDO.getSourceClusterId()).getCode());
    metaData.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, taskDO.getSourceClusterId());
    temp.setMetadata(metaData);
    return temp;
}
 
Example #29
Source File: NacosSyncToEurekaServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private InstanceInfo buildSyncInstance(Instance instance, TaskDO taskDO) {
    DataCenterInfo dataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn);
    HashMap<String, String> metadata = new HashMap<>(16);
    metadata.put(SkyWalkerConstants.DEST_CLUSTERID_KEY, taskDO.getDestClusterId());
    metadata.put(SkyWalkerConstants.SYNC_SOURCE_KEY, skyWalkerCacheServices.getClusterType(taskDO.getSourceClusterId()).getCode());
    metadata.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, taskDO.getSourceClusterId());
    String homePageUrl = "http://" + instance.getIp() + ":" + instance.getPort();
    String serviceName = taskDO.getServiceName();

    return new InstanceInfo(
            instance.getIp() + ":" + serviceName + ":" + instance.getPort(),
            serviceName,
            null,
            instance.getIp(),
            null,
            new InstanceInfo.PortWrapper(true, instance.getPort()),
            null,
            homePageUrl,
            homePageUrl + "/info",
            homePageUrl + "/health",
            null,
            serviceName,
            serviceName,
            1,
            dataCenterInfo,
            instance.getIp(),
            InstanceInfo.InstanceStatus.UP,
            InstanceInfo.InstanceStatus.UNKNOWN,
            null,
            new LeaseInfo(30, 90,
                    0L, 0L, 0L, 0L, 0L),
            false,
            metadata,
            System.currentTimeMillis(),
            System.currentTimeMillis(),
            null,
            null
    );
}
 
Example #30
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private Instance buildSyncInstance(HealthService instance, TaskDO taskDO) {
    Instance temp = new Instance();
    temp.setIp(instance.getService().getAddress());
    temp.setPort(instance.getService().getPort());
    Map<String, String> metaData = new HashMap<>(ConsulUtils.transferMetadata(instance.getService().getTags()));
    metaData.put(SkyWalkerConstants.DEST_CLUSTERID_KEY, taskDO.getDestClusterId());
    metaData.put(SkyWalkerConstants.SYNC_SOURCE_KEY,
        skyWalkerCacheServices.getClusterType(taskDO.getSourceClusterId()).getCode());
    metaData.put(SkyWalkerConstants.SOURCE_CLUSTERID_KEY, taskDO.getSourceClusterId());
    temp.setMetadata(metaData);
    return temp;
}