com.alibaba.nacos.api.naming.NamingService Java Examples

The following examples show how to use com.alibaba.nacos.api.naming.NamingService. 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: NacosSyncToZookeeperServiceImpl.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());
        EventListener eventListener = nacosListenerMap.remove(taskDO.getTaskId());
        PathChildrenCache pathChildrenCache = pathChildrenCacheMap.get(taskDO.getTaskId());
        sourceNamingService.unsubscribe(taskDO.getServiceName(), eventListener);
        CloseableUtils.closeQuietly(pathChildrenCache);
        Set<String> instanceUrlSet = instanceBackupMap.get(taskDO.getTaskId());
        CuratorFramework client = zookeeperServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName());
        for (String instanceUrl : instanceUrlSet) {
            client.delete().quietly().forPath(instanceUrl);
        }
    } catch (Exception e) {
        log.error("delete task from nacos to zk was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #2
Source File: CacheableEventPublishingNacosServiceFactory.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void publishDeferService(ApplicationContext context) throws NacosException {
	setApplicationContext(context);
	for (DeferServiceHolder holder : deferServiceCache) {
		final Object o = holder.getHolder();
		final Properties properties = holder.getProperties();
		if (o instanceof ConfigService) {
			ConfigService configService = (ConfigService) o;
			createWorkerManager.get(ServiceType.CONFIG).run(properties,
					configService);
		}
		else if (o instanceof NamingService) {
			NamingService namingService = (NamingService) o;
			createWorkerManager.get(ServiceType.NAMING).run(properties,
					namingService);
		}
		else if (o instanceof NamingMaintainService) {
			NamingMaintainService maintainService = (NamingMaintainService) o;
			createWorkerManager.get(ServiceType.MAINTAIN).run(properties,
					maintainService);
		}
	}
	deferServiceCache.clear();
}
 
Example #3
Source File: EurekaSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sync(TaskDO taskDO) {
    try {
        EurekaNamingService eurekaNamingService = eurekaServerHolder.get(taskDO.getSourceClusterId(), null);
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        List<InstanceInfo> eurekaInstances = eurekaNamingService.getApplications(taskDO.getServiceName());
        List<Instance> nacosInstances = destNamingService.getAllInstances(taskDO.getServiceName());

        if (CollectionUtils.isEmpty(eurekaInstances)) {
            // Clear all instance from Nacos
            deleteAllInstance(taskDO, destNamingService, nacosInstances);
        } else {
            if (!CollectionUtils.isEmpty(nacosInstances)) {
                // Remove invalid instance from Nacos
                removeInvalidInstance(taskDO, destNamingService, eurekaInstances, nacosInstances);
            }
            addValidInstance(taskDO, destNamingService, eurekaInstances);
        }
        specialSyncEventBus.subscribe(taskDO, this::sync);
    } catch (Exception e) {
        log.error("sync task from eureka to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.SYNC_ERROR);
        return false;
    }
    return true;
}
 
Example #4
Source File: EurekaSyncToNacosServiceImpl.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(), taskDO.getNameSpace());
        List<Instance> allInstances = destNamingService.getAllInstances(taskDO.getServiceName());
        deleteAllInstance(taskDO, destNamingService, allInstances);

    } catch (Exception e) {
        log.error("delete a task from eureka to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
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: NacosSyncQueryClientImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public List<TaskModel> getAllInstance(InstanceQueryModel instanceQueryModel) {
    NamingService namingService = nacosServerHolder
            .get(instanceQueryModel.getSourceClusterId(), instanceQueryModel.getGroupName());
    try {
        ListView<String> servicesOfServer = namingService
                .getServicesOfServer(instanceQueryModel.getPageNo(),
                        instanceQueryModel.getPageSize());
        return servicesOfServer.getData().stream()
                .map(serviceName -> buildTaskModel(instanceQueryModel, serviceName))
                .collect(Collectors.toList());

    } catch (NacosException e) {
        log.error("When using nacos client failure query tasks", e);
        return Collections.emptyList();
    }
}
 
Example #7
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 #8
Source File: NacosSyncToEurekaServiceImpl.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());
        EurekaNamingService destNamingService =
                eurekaServerHolder.get(taskDO.getDestClusterId(), taskDO.getGroupName());

        sourceNamingService.unsubscribe(taskDO.getServiceName(), nacosListenerMap.get(taskDO.getTaskId()));
        // 删除目标集群中同步的实例列表
        List<InstanceInfo> allInstances = destNamingService.getApplications(taskDO.getServiceName());
        if (allInstances != null) {
            for (InstanceInfo instance : allInstances) {
                if (needDelete(instance.getMetadata(), taskDO)) {
                    destNamingService.deregisterInstance(instance);
                }
            }
        }
    } catch (Exception e) {
        log.error("delete task from nacos to eureka was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.DELETE_ERROR);
        return false;
    }
    return true;
}
 
Example #9
Source File: ServiceProvider.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws NacosException {
    Properties properties = new Properties();
    properties.setProperty("serverAddr", Constants.NACOS_SERVER_ADDRESS);
    properties.setProperty("namespace", Constants.NAMESPACE);

    NamingService naming = NamingFactory.createNamingService(properties);

    naming.registerInstance(Constants.SERVICE_NAME, Constants.IP_1, Constants.PORT_1, Constants.CLUSTER_NAME_1);
    naming.registerInstance(Constants.SERVICE_NAME, Constants.IP_2, Constants.PORT_2, Constants.CLUSTER_NAME_2);
    List<Instance> instances = naming.getAllInstances(Constants.SERVICE_NAME);
    System.out.println("getAllInstances after registered\ninstance size="
            + instances.size() + "\ninstance list=" + instances);
    try {
        int in = System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #10
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 #11
Source File: NacosDiscoveryHealthIndicator.java    From nacos-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	builder.up();
	NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
			.getSingleton();
	for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
		if (namingService instanceof NacosServiceMetaData) {
			NacosServiceMetaData nacosServiceMetaData = (NacosServiceMetaData) namingService;
			Properties properties = nacosServiceMetaData.getProperties();
			builder.withDetail(
					JSON.toJSONString(
							PropertiesUtils.extractSafeProperties(properties)),
					namingService.getServerStatus());
		}
		if (!namingService.getServerStatus().equalsIgnoreCase(UP_STATUS)) {
			builder.down();
		}
	}
}
 
Example #12
Source File: NacosServerListTests.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testEmptyInstancesReturnsEmptyList() throws Exception {
	NacosDiscoveryProperties nacosDiscoveryProperties = mock(
			NacosDiscoveryProperties.class);

	NamingService namingService = mock(NamingService.class);

	when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
	when(namingService.selectInstances(anyString(), eq("DEFAULT"), eq(true)))
			.thenReturn(null);

	NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
	List<NacosServer> servers = serverList.getInitialListOfServers();
	assertThat(servers).isEmpty();
}
 
Example #13
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 #14
Source File: NacosDiscoveryEndpoint.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
/**
 * @return nacos discovery endpoint
 */
@ReadOperation
public Map<String, Object> nacosDiscovery() {
	Map<String, Object> result = new HashMap<>();
	result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);

	NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
	List<ServiceInfo> subscribe = Collections.emptyList();

	try {
		subscribe = namingService.getSubscribeServices();
	}
	catch (Exception e) {
		log.error("get subscribe services from nacos fail,", e);
	}
	result.put("subscribe", subscribe);
	return result;
}
 
Example #15
Source File: NacosServiceRegistry.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Override
public void deregister(Registration registration) {

	log.info("De-registering from Nacos Server now...");

	if (StringUtils.isEmpty(registration.getServiceId())) {
		log.warn("No dom to de-register for nacos client...");
		return;
	}

	NamingService namingService = namingService();
	String serviceId = registration.getServiceId();
	String group = nacosDiscoveryProperties.getGroup();

	try {
		namingService.deregisterInstance(serviceId, group, registration.getHost(),
				registration.getPort(), nacosDiscoveryProperties.getClusterName());
	}
	catch (Exception e) {
		log.error("ERR_NACOS_DEREGISTER, de-register failed...{},",
				registration.toString(), e);
	}

	log.info("De-registration finished.");
}
 
Example #16
Source File: ZookeeperSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
private void processEvent(TaskDO taskDO, NamingService destNamingService, PathChildrenCacheEvent event, String path,
    Map<String, String> queryParam) throws NacosException {
    Map<String, String> ipAndPortParam = parseIpAndPortString(path);
    Instance instance = buildSyncInstance(queryParam, ipAndPortParam, taskDO);
    switch (event.getType()) {
        case CHILD_ADDED:
        case CHILD_UPDATED:

            destNamingService.registerInstance(
                getServiceNameFromCache(taskDO.getTaskId(), queryParam), instance);
            break;
        case CHILD_REMOVED:

            destNamingService.deregisterInstance(
                getServiceNameFromCache(taskDO.getTaskId(), queryParam),
                ipAndPortParam.get(INSTANCE_IP_KEY),
                Integer.parseInt(ipAndPortParam.get(INSTANCE_PORT_KEY)));
            nacosServiceNameMap.remove(taskDO.getTaskId());
            break;
        default:
            break;
    }
}
 
Example #17
Source File: ConsulSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 6 votes vote down vote up
@Override
public boolean sync(TaskDO taskDO) {
    try {
        ConsulClient consulClient = consulServerHolder.get(taskDO.getSourceClusterId(), null);
        NamingService destNamingService = nacosServerHolder.get(taskDO.getDestClusterId(), null);
        Response<List<HealthService>> response =
            consulClient.getHealthServices(taskDO.getServiceName(), true, QueryParams.DEFAULT);
        List<HealthService> healthServiceList = response.getValue();
        Set<String> instanceKeys = new HashSet<>();
        overrideAllInstance(taskDO, destNamingService, healthServiceList, instanceKeys);
        cleanAllOldInstance(taskDO, destNamingService, instanceKeys);
        specialSyncEventBus.subscribe(taskDO, this::sync);
    } catch (Exception e) {
        log.error("Sync task from consul to nacos was failed, taskId:{}", taskDO.getTaskId(), e);
        metricsManager.recordError(MetricsStatisticsType.SYNC_ERROR);
        return false;
    }
    return true;
}
 
Example #18
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 #19
Source File: ServiceConsumer.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws NacosException {
    Properties properties = new Properties();
    properties.setProperty("serverAddr", Constants.NACOS_SERVER_ADDRESS);
    properties.setProperty("namespace", Constants.NAMESPACE);

    NamingService naming = NamingFactory.createNamingService(properties);
    naming.subscribe(Constants.SERVICE_NAME, new EventListener() {
        @Override
        public void onEvent(Event event) {
            NamingEvent namingEvent = (NamingEvent) event;
            printInstances(namingEvent);
            mockConsume(naming, Constants.SERVICE_NAME);
        }
    });
    try {
        int in = System.in.read();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #20
Source File: CacheableEventPublishingNacosServiceFactory.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public NamingService createNamingService(Properties properties)
		throws NacosException {
	Properties copy = new Properties();
	copy.putAll(properties);
	return (NamingService) createWorkerManager.get(ServiceType.NAMING).run(copy,
			null);
}
 
Example #21
Source File: ZookeeperSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private void registerAllInstances(TaskDO taskDO, PathChildrenCache pathChildrenCache,
    NamingService destNamingService) throws NacosException {
    List<ChildData> currentData = pathChildrenCache.getCurrentData();
    for (ChildData childData : currentData) {
        String path = childData.getPath();
        Map<String, String> queryParam = parseQueryString(childData.getPath());
        if (isMatch(taskDO, queryParam) && needSync(queryParam)) {
            Map<String, String> ipAndPortParam = parseIpAndPortString(path);
            Instance instance = buildSyncInstance(queryParam, ipAndPortParam, taskDO);
            destNamingService.registerInstance(getServiceNameFromCache(taskDO.getTaskId(), queryParam),
                instance);
        }
    }
}
 
Example #22
Source File: CacheableNacosInjectedFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNamingService() throws NacosException, InterruptedException {
	NamingService namingService = nacosServiceFactory.createNamingService(properties);
	NamingService namingService2 = nacosServiceFactory
			.createNamingService(properties2);
	// throws java.lang.AssertionError
	Assert.assertTrue(namingService != namingService2);
}
 
Example #23
Source File: NacosDiscoveryEndpoint.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@ReadOperation
public Map<String, Object> invoke() {
	Map<String, Object> result = new HashMap<>(8);

	result.put("nacosDiscoveryGlobalProperties",
			PropertiesUtils.extractSafeProperties(applicationContext.getBean(
					DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME, Properties.class)));

	NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
			.getSingleton();

	JSONArray array = new JSONArray();
	for (NamingService namingService : nacosServiceFactory.getNamingServices()) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("servicesOfServer",
					namingService.getServicesOfServer(0, PAGE_SIZE));
			jsonObject.put("subscribeServices", namingService.getSubscribeServices());
			array.add(jsonObject);
		}
		catch (Exception e) {
			jsonObject.put("serverStatus", namingService.getServerStatus() + ": "
					+ NacosUtils.SEPARATOR + e.getMessage());
		}
	}

	result.put("namingServersStatus", array);
	return result;
}
 
Example #24
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 #25
Source File: NacosServiceDiscoveryTest.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetServices() throws NacosException {
	ListView<String> nacosServices = new ListView<>();

	nacosServices.setData(new LinkedList<>());

	nacosServices.getData().add(serviceName + "1");
	nacosServices.getData().add(serviceName + "2");
	nacosServices.getData().add(serviceName + "3");

	NacosDiscoveryProperties nacosDiscoveryProperties = mock(
			NacosDiscoveryProperties.class);

	NamingService namingService = mock(NamingService.class);

	when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
	when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
	when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),
			eq("DEFAULT"))).thenReturn(nacosServices);

	NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery(
			nacosDiscoveryProperties);

	List<String> services = serviceDiscovery.getServices();

	assertThat(services.size()).isEqualTo(3);
	assertThat(services.contains(serviceName + "1"));
	assertThat(services.contains(serviceName + "2"));
	assertThat(services.contains(serviceName + "3"));
}
 
Example #26
Source File: NacosServiceRegistry.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public void register(Registration registration) {

	if (StringUtils.isEmpty(registration.getServiceId())) {
		log.warn("No service to register for nacos client...");
		return;
	}

	NamingService namingService = namingService();
	String serviceId = registration.getServiceId();
	String group = nacosDiscoveryProperties.getGroup();

	Instance instance = getNacosInstanceFromRegistration(registration);

	try {
		namingService.registerInstance(serviceId, group, instance);
		log.info("nacos registry, {} {} {}:{} register finished", group, serviceId,
				instance.getIp(), instance.getPort());
	}
	catch (Exception e) {
		log.error("nacos registry, {} register failed...{},", serviceId,
				registration.toString(), e);
		// rethrow a RuntimeException if the registration is failed.
		// issue : https://github.com/alibaba/spring-cloud-alibaba/issues/1132
		rethrowRuntimeException(e);
	}
}
 
Example #27
Source File: NacosDiscoveryProperties.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
public NamingService namingServiceInstance() {

		if (null != namingService) {
			return namingService;
		}

		try {
			namingService = NacosFactory.createNamingService(getNacosProperties());
		}
		catch (Exception e) {
			log.error("create naming service error!properties={},e=,", this, e);
			return null;
		}
		return namingService;
	}
 
Example #28
Source File: CacheableEventPublishingNacosServiceFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNamingService() throws NacosException {
	NamingService namingService = nacosServiceFactory.createNamingService(properties);
	NamingService namingService2 = nacosServiceFactory
			.createNamingService(properties);
	Assert.assertTrue(namingService == namingService2);
}
 
Example #29
Source File: NacosServerListTests.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateServers() throws Exception {
	ArrayList<Instance> instances = new ArrayList<>();

	HashMap<String, String> map = new HashMap<>();
	map.put("instanceNum", "1");
	instances.add(NacosMockTest.serviceInstance("test-service", true, map));

	NacosDiscoveryProperties nacosDiscoveryProperties = mock(
			NacosDiscoveryProperties.class);

	NamingService namingService = mock(NamingService.class);

	when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
	when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
	when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
			.thenReturn(instances.stream().filter(Instance::isHealthy)
					.collect(Collectors.toList()));

	IClientConfig clientConfig = mock(IClientConfig.class);
	when(clientConfig.getClientName()).thenReturn("test-service");
	NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
	serverList.initWithNiwsConfig(clientConfig);

	List<NacosServer> servers = serverList.getUpdatedListOfServers();
	assertThat(servers).hasSize(1);

	assertThat(servers.get(0).getInstance().isHealthy()).isEqualTo(true);
	assertThat(servers.get(0).getInstance().getMetadata().get("instanceNum"))
			.isEqualTo("1");
}
 
Example #30
Source File: CacheableEventPublishingNacosServiceFactory.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public NamingService run(Properties properties, NamingService service)
		throws NacosException {
	String cacheKey = identify(properties);
	NamingService namingService = namingServicesCache.get(cacheKey);

	if (namingService == null) {
		if (service == null) {
			service = NacosFactory.createNamingService(properties);
		}
		namingService = new DelegatingNamingService(service, properties);
		namingServicesCache.put(cacheKey, namingService);
	}
	return namingService;
}