com.alibaba.nacos.api.exception.NacosException Java Examples

The following examples show how to use com.alibaba.nacos.api.exception.NacosException. 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: NacosDynRouteLocator.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 添加Nacos监听
 */
private void addListener() {
    try {
        nacosConfigProperties.configServiceInstance().addListener(ZUUL_DATA_ID, ZUUL_GROUP_ID, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            @Override
            public void receiveConfigInfo(String configInfo) {
                //赋值路由信息
                locator.setZuulRouteEntities(getListByStr(configInfo));
                RoutesRefreshedEvent routesRefreshedEvent = new RoutesRefreshedEvent(locator);
                publisher.publishEvent(routesRefreshedEvent);
            }
        });
    } catch (NacosException e) {
        log.error("nacos-addListener-error", e);
    }
}
 
Example #2
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
private void subscribeEventListener(String serviceName) {
	if (listeningServices.add(serviceName)) {
		try {
			String group = nacosDiscoveryProperties.getGroup();
			namingService.subscribe(serviceName, group, event -> {
				if (event instanceof NamingEvent) {
					NamingEvent namingEvent = (NamingEvent) event;
					List<ServiceInstance> serviceInstances = hostToServiceInstanceList(
							namingEvent.getInstances(), serviceName);
					dispatchServiceInstancesChangedEvent(serviceName,
							serviceInstances);
				}
			});
		}
		catch (NacosException e) {
			ReflectionUtils.rethrowRuntimeException(e);
		}
	}
}
 
Example #3
Source File: NacosUtil.java    From anyline with Apache License 2.0 6 votes vote down vote up
/**
 * 读取配置文件 并 监听配置更新
 * @param group group
 * @param data data
 * @param listener listent
 * @return String
 * @throws NacosException NacosException
 */
public String config(String group, String data, Listener listener) throws NacosException{
	if(BasicUtil.isEmpty(group)){
		group = config.GROUP;
	}
	log.warn("[nacos config][group:{}][data:{}][listener:{}]", group, data, listener);
	Properties properties = new Properties();
	properties.put(PropertyKeyConst.NAMESPACE, config.NAMESPACE);
	properties.put(PropertyKeyConst.SERVER_ADDR, config.ADDRESS+":"+config.PORT);
	ConfigService configService = NacosFactory.createConfigService(properties);
	String content = configService.getConfig(data, group, config.TIMEOUT);
	if(null != listener) {
		configService.addListener(data, group, listener);
	}
	return content;
}
 
Example #4
Source File: MockConfigService.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@Override
public boolean publishConfig(String dataId, String group, final String content)
		throws NacosException {
	String key = createKey(dataId, group);
	contentCache.put(key, content);

	List<Listener> listeners = listenersCache.get(key);
	if (!CollectionUtils.isEmpty(listeners)) {
		for (final Listener listener : listeners) {
			Executor executor = listener.getExecutor();
			if (executor != null) {
				executor.execute(new Runnable() {
					@Override
					public void run() {
						listener.receiveConfigInfo(content);
					}
				});
			}
			else {
				listener.receiveConfigInfo(content);
			}
		}
	}

	return true;
}
 
Example #5
Source File: CacheableEventPublishingNacosServiceFactory.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@Override
public ConfigService run(Properties properties, ConfigService service)
		throws NacosException {
	String cacheKey = identify(properties);
	ConfigService configService = configServicesCache.get(cacheKey);

	if (configService == null) {
		if (service == null) {
			service = NacosFactory.createConfigService(properties);
		}
		configService = new EventPublishingConfigService(service, properties,
				getSingleton().context,
				getSingleton().nacosConfigListenerExecutor);
		configServicesCache.put(cacheKey, configService);
	}
	return configService;
}
 
Example #6
Source File: AbstractNacosConfigService.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
private boolean publishConfig() {
    StringBuilder sb = new StringBuilder();
    int size = configMap.size();
    int index = 1;
    for (Map.Entry<String, NacosConfig> entry : configMap.entrySet()) {
        sb.append(entry.getKey())
                .append("=")
                .append(entry.getValue().getValue());
        if (index++ < size) {
            sb.append("\n");
        }
    }
    String newContent = sb.toString();
    try {
        configService.publishConfig(dataId, group, newContent);
    } catch (NacosException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
 
Example #7
Source File: EventPublishingConfigServiceTest.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@Test(expected = NacosException.class)
public void testGetConfigOnTimeout() throws NacosException {
	final long timeout = -1L;
	context.addApplicationListener(
			new ApplicationListener<NacosConfigTimeoutEvent>() {
				@Override
				public void onApplicationEvent(NacosConfigTimeoutEvent event) {
					assertNacosConfigEvent(event);
					Assert.assertEquals(timeout, event.getTimeout());
					Assert.assertEquals(TIMEOUT_ERROR_MESSAGE,
							event.getErrorMessage());
				}
			});

	configService.getConfig(DATA_ID, GROUP_ID, timeout); // trigger timeout error
}
 
Example #8
Source File: EventPublishingConfigServiceTest.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveConfigWithEvent() throws NacosException {

	context.addApplicationListener(
			new ApplicationListener<NacosConfigRemovedEvent>() {
				@Override
				public void onApplicationEvent(NacosConfigRemovedEvent event) {
					assertNacosConfigEvent(event);
					Assert.assertTrue(event.isRemoved());
				}
			});

	configService.publishConfig(DATA_ID, GROUP_ID, CONTENT);
	configService.removeConfig(DATA_ID, GROUP_ID);

}
 
Example #9
Source File: AbstractNacosServiceBeanBuilder.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
public S build(Map<String, Object> nacosPropertiesAttributes) {

		NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(beanFactory);
		Properties properties = resolveProperties(nacosPropertiesAttributes);

		if (properties.isEmpty()) {
			throw new BeanCreationException(
					format("The @%s attributes must be configured",
							NacosProperties.class.getSimpleName()));
		}

		try {
			return createService(nacosServiceFactory, properties);
		}
		catch (NacosException e) {
			throw new BeanCreationException(e.getErrMsg(), e);
		}
	}
 
Example #10
Source File: PropertiesAssemble.java    From spring-cloud-zuul-nacos with Apache License 2.0 6 votes vote down vote up
private List<ZuulRouteEntity> listenerNacos (String dataId, String group) {
		try {
			Properties properties = new Properties();
			properties.put(PropertyKeyConst.SERVER_ADDR, "localhost:8848");
			ConfigService configService = NacosFactory.createConfigService(properties);
			String content = configService.getConfig(dataId, group, 5000);
			System.out.println("从Nacos返回的配置:" + content);
			//注册Nacos配置更新监听器
//            configService.addListener(dataId, group, new Listener()  {
//                @Override
//                public void receiveConfigInfo(String configInfo) {
//                    System.out.println("Nacos更新了!");
//
//                }
//                @Override
//                public Executor getExecutor() {
//                    return null;
//                }
//            });
			return JSONObject.parseArray(content, ZuulRouteEntity.class);
		} catch (NacosException e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}
 
Example #11
Source File: EventPublishingConfigServiceTest.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemoveListener() throws NacosException {
	final Listener listener = new AbstractListener() {
		@Override
		public void receiveConfigInfo(String configInfo) {
		}
	};

	// assert NacosConfigListenerRegisteredEvent
	context.addApplicationListener(
			new ApplicationListener<NacosConfigListenerRegisteredEvent>() {
				@Override
				public void onApplicationEvent(
						NacosConfigListenerRegisteredEvent event) {
					assertNacosConfigEvent(event);
					Assert.assertFalse(event.isRegistered());
					Assert.assertEquals(listener, event.getListener());
				}
			});

	configService.removeListener(DATA_ID, GROUP_ID, listener);

}
 
Example #12
Source File: NacosCenterRepository.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
/**
 * Watch key or path of the config server.
 *
 * @param key key of data
 * @param dataChangedEventListener data changed event listener
 */
@Override
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
    try {
        String dataId = ConfigKeyUtils.pathToKey(key);
        String group = nacosProperties.getValue(NacosPropertyKey.GROUP);
        configService.addListener(dataId, group, new Listener() {
            
            @Override
            public Executor getExecutor() {
                return null;
            }
            
            @Override
            public void receiveConfigInfo(final String configInfo) {
                dataChangedEventListener.onChange(new DataChangedEvent(key, configInfo, DataChangedEvent.ChangedType.UPDATED));
            }
        });
    } catch (final NacosException ex) {
        log.debug("Nacos watch key exception for: {}", ex.toString());
    }
}
 
Example #13
Source File: ConfigServiceController.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/publish", method = POST)
@ResponseBody
public boolean publish(@RequestParam String dataId,
		@RequestParam(defaultValue = DEFAULT_GROUP) String groupId,
		@RequestParam String content) throws NacosException {
	return configService.publishConfig(dataId, groupId, content);
}
 
Example #14
Source File: EurekaSyncToNacosServiceImpl.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
private void deleteAllInstance(TaskDO taskDO, NamingService destNamingService, List<Instance> allInstances)
    throws NacosException {
    for (Instance instance : allInstances) {
        if (needDelete(instance.getMetadata(), taskDO)) {
            destNamingService.deregisterInstance(taskDO.getServiceName(), instance);
        }

    }
}
 
Example #15
Source File: NacosNamingServiceUtils.java    From dubbo-registry-nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Create an instance of {@link NamingService} from specified {@link URL connection url}
 *
 * @param connectionURL {@link URL connection url}
 * @return {@link NamingService}
 * @since 2.7.5
 */
public static NamingService createNamingService(URL connectionURL) {
    Properties nacosProperties = buildNacosProperties(connectionURL);
    NamingService namingService;
    try {
        namingService = NacosFactory.createNamingService(nacosProperties);
    } catch (NacosException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getErrMsg(), e);
        }
        throw new IllegalStateException(e);
    }
    return namingService;
}
 
Example #16
Source File: MockConfigService.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(String dataId, String group, Listener listener)
		throws NacosException {
	String key = createKey(dataId, group);
	List<Listener> listeners = listenersCache.get(key);
	if (listeners == null) {
		listeners = new LinkedList<Listener>();
		listenersCache.put(key, listeners);
	}
	listeners.add(listener);
}
 
Example #17
Source File: CacheableEventPublishingNacosServiceFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateConfigService() throws NacosException {
	ConfigService configService = nacosServiceFactory.createConfigService(properties);
	ConfigService configService2 = nacosServiceFactory
			.createConfigService(properties);
	Assert.assertTrue(configService == configService2);
}
 
Example #18
Source File: NacosReactiveDiscoveryClient.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private Function<String, Publisher<ServiceInstance>> loadInstancesFromNacos() {
	return serviceId -> {
		try {
			return Flux.fromIterable(serviceDiscovery.getInstances(serviceId));
		}
		catch (NacosException e) {
			log.error("get service instance[{}] from nacos error!", serviceId, e);
			return Flux.empty();
		}
	};
}
 
Example #19
Source File: NacosRateLimiterConfigCentre.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * load rate limiter config data
 *
 * @return config data
 * @throws ApiBootException ApiBoot Exception
 */
protected String loadConfigData() throws ApiBootException {
    try {
        return configService.getConfig(DATA_ID, Constants.DEFAULT_GROUP, NacosUtils.DEFAULT_TIMEOUT);
    } catch (NacosException e) {
        logger.error(e.getMessage(), e);
    }
    throw new ApiBootException("Load ApiBoot RateLimiter config data fail.");
}
 
Example #20
Source File: EventPublishingConfigService.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public void addListener(String dataId, String group, Listener listener)
		throws NacosException {
	configService.addListener(dataId, group, listener);
	publishEvent(new NacosConfigListenerRegisteredEvent(configService, dataId, group,
			listener, true));
}
 
Example #21
Source File: CacheableNacosInjectedFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateConfigService() throws NacosException {
	ConfigService configService = nacosServiceFactory.createConfigService(properties);
	ConfigService configService2 = nacosServiceFactory
			.createConfigService(properties2);
	// throws java.lang.AssertionError
	Assert.assertTrue(configService != configService2);
}
 
Example #22
Source File: NacosDiscoveryAutoRegister.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {

    if (!discoveryProperties.isAutoRegister()) {
        return;
    }

    Register register = discoveryProperties.getRegister();

    if (StringUtils.isEmpty(register.getIp())) {
        register.setIp(NetUtils.localIP());
    }

    if (register.getPort() == 0) {
        register.setPort(event.getWebServer().getPort());
    }

    register.getMetadata().put("preserved.register.source", "SPRING_BOOT");

    register.setInstanceId("");

    String serviceName = register.getServiceName();

    if (StringUtils.isEmpty(serviceName)){
        if (StringUtils.isEmpty(applicationName)){
            throw new AutoRegisterException("serviceName notNull");
        }
        serviceName = applicationName;
    }

    try {
        namingService.registerInstance(serviceName, register.getGroupName(),
                register);
        logger.info("Finished auto register service : {}, ip : {}, port : {}",
                serviceName, register.getIp(), register.getPort());
    } catch (NacosException e) {
        throw new AutoRegisterException(e);
    }
}
 
Example #23
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 #24
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 #25
Source File: NacosCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Get data from nacos instance.
 *
 * @param key key of data
 * @return value of data
 */
@Override
public String get(final String key) {
    try {
        String dataId = ConfigKeyUtils.pathToKey(key);
        String group = nacosProperties.getValue(NacosPropertyKey.GROUP);
        long timeoutMs = nacosProperties.getValue(NacosPropertyKey.TIMEOUT);
        return configService.getConfig(dataId, group, timeoutMs);
    } catch (final NacosException ex) {
        log.debug("Nacos get config value exception for: {}", ex.toString());
        return null;
    }
}
 
Example #26
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatchUpdatedChangedType() throws NacosException {
    final String expectValue = "expectValue";
    final String[] actualValue = {null};
    final ChangedType[] actualType = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(expectValue))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> {
        actualValue[0] = dataChangedEvent.getValue();
        actualType[0] = dataChangedEvent.getChangedType();
    };
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualValue[0], is(expectValue));
    assertThat(actualType[0], is(ChangedType.UPDATED));
}
 
Example #27
Source File: NacosConfigListenerMethodProcessorTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testPublishConfig() throws NacosException, InterruptedException {
	configService.publishConfig(DATA_ID, DEFAULT_GROUP, "9527");

	Thread.sleep(3000);

	assertNull(listeners.getIntegerValue()); // asserts true
	assertEquals(Double.valueOf(9527), listeners.getDoubleValue()); // asserts true
}
 
Example #28
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 #29
Source File: MultRegisterCenterServerMgmtConfig.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Bean
public MultRegisterCenter initMultNacos() {
    URL_MAP.put("nacos1","127.0.0.1:8848");
    Map<String, NamingService> multEurekaMap = Maps.newConcurrentMap();
    Map<String, MossNacosAutoServiceRegistration> multRegistrationMap = Maps.newConcurrentMap();
    Map<NamingService, HeartbeatMonitor> multHeartbeatMonitorMap=new ConcurrentHashMap<NamingService, HeartbeatMonitor>();
    URL_MAP.entrySet().forEach(e -> {
        NacosDiscoveryProperties nacosDiscoveryProperties=new NacosDiscoveryProperties();
        nacosDiscoveryProperties.setService("halo-moss");
        nacosDiscoveryProperties.setServerAddr(e.getValue());
        try {
            NamingService namingService=NacosFactory.createNamingService(e.getValue());
            com.alibaba.nacos.api.naming.pojo.Instance instance = new com.alibaba.nacos.api.naming.pojo.Instance();
            instance.setIp(inetUtils.findFirstNonLoopbackHostInfo().getIpAddress());
            instance.setPort(-1);
            instance.setWeight(1);
            instance.setClusterName("DEFAULT");
            namingService.registerInstance("halo-moss", instance);
            this.context.publishEvent(
                    new InstanceRegisteredEvent<>(this, namingService));
            multEurekaMap.put(e.getKey(),namingService);
            multHeartbeatMonitorMap.put(namingService,new HeartbeatMonitor());
        } catch (NacosException e1) {
            e1.printStackTrace();
        }
        //NacosServiceRegistry serviceRegistry=new NacosServiceRegistry();
        //AutoServiceRegistrationProperties autoServiceRegistrationProperties=new AutoServiceRegistrationProperties();
        //MossNacosAutoServiceRegistration autoServiceRegistration = new MossNacosAutoServiceRegistration(serviceRegistry,autoServiceRegistrationProperties,registration,registration);
        //autoServiceRegistration.setRegistration(registration);
        //multRegistrationMap.put(e.getKey(), autoServiceRegistration);

    });
    multRegisterCenter = new MultRegisterCenter(multEurekaMap, multRegistrationMap,multHeartbeatMonitorMap);
    return multRegisterCenter;
}
 
Example #30
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
@Test
public void assertDeleteWhenThrowException() {
    when(configService.getConfig(eq("sharding.test"), eq(group), anyLong())).thenReturn("value");
    doThrow(NacosException.class).when(configService).removeConfig(eq("sharding.test"), eq(group));
    REPOSITORY.delete("/sharding/test");
    assertNotNull(REPOSITORY.get("/sharding/test"));
}