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

The following examples show how to use com.alibaba.nacos.api.exception.NacosException. These examples are extracted from open source projects. 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
/**
 * 添加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 Project: anyline   Source File: NacosUtil.java    License: 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 3
@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 4
Source Project: nacos-tutorial   Source File: AbstractNacosConfigService.java    License: 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 5
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 6
@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 7
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 8
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 9
Source Project: nacos-spring-project   Source File: MockConfigService.java    License: 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 10
@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 11
Source Project: shardingsphere   Source File: NacosCenterRepository.java    License: 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 12
@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 13
@Override
public Flux<RouteDefinition> getRouteDefinitions() {
    try {
        String content = nacosConfigProperties.configServiceInstance().getConfig(SCG_DATA_ID, SCG_GROUP_ID,5000);
        List<RouteDefinition> routeDefinitions = getListByStr(content);
        return Flux.fromIterable(routeDefinitions);
    } catch (NacosException e) {
        log.error("getRouteDefinitions by nacos error", e);
    }
    return Flux.fromIterable(CollUtil.newArrayList());
}
 
Example 14
Source Project: Moss   Source File: MultRegisterCenterServerMgmtConfig.java    License: 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 15
@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 16
@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 17
Source Project: api-boot   Source File: NacosRateLimiterConfigCentre.java    License: 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 18
Source Project: shardingsphere   Source File: NacosCenterRepositoryTest.java    License: 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"));
}
 
Example 19
Source Project: nacos-spring-project   Source File: MockConfigService.java    License: 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 20
/**
 * 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 21
Source Project: nacos-sync   Source File: EurekaSyncToNacosServiceImpl.java    License: 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 22
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 23
Source Project: shardingsphere   Source File: NacosCenterRepository.java    License: 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 24
@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 25
@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 26
@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 27
@Override
public void registerInstance(String applicationName, String ip, Integer port) {
	try {
		this.sidecarNacosDiscoveryProperties.namingServiceInstance().registerInstance(
				applicationName, sidecarNacosDiscoveryProperties.getGroup(), ip,
				port);
	}
	catch (NacosException e) {
		log.warn("nacos exception happens", e);
	}
}
 
Example 28
Source Project: shardingsphere   Source File: NacosCenterRepositoryTest.java    License: 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 29
@Test
public void testCreateConfigService() throws NacosException {
	ConfigService configService = nacosServiceFactory.createConfigService(properties);
	ConfigService configService2 = nacosServiceFactory
			.createConfigService(properties);
	Assert.assertTrue(configService == configService2);
}
 
Example 30
@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
}