Java Code Examples for com.alibaba.nacos.api.config.ConfigService#addListener()

The following examples show how to use com.alibaba.nacos.api.config.ConfigService#addListener() . 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: 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 2
Source File: DynamicRouteServiceImplByNacos.java    From spring-cloud-gateway-nacos with Apache License 2.0 6 votes vote down vote up
/**
 * 监听Nacos Server下发的动态路由配置
 * @param dataId
 * @param group
 */
public void dynamicRouteByNacosListener (String dataId, String group){
    try {
        ConfigService configService=NacosFactory.createConfigService("127.0.0.1:8848");
        String content = configService.getConfig(dataId, group, 5000);
        System.out.println(content);
        configService.addListener(dataId, group, new Listener()  {
            @Override
            public void receiveConfigInfo(String configInfo) {
                RouteDefinition definition= JSON.parseObject(configInfo,RouteDefinition.class);
                dynamicRouteService.update(definition);
            }
            @Override
            public Executor getExecutor() {
                return null;
            }
        });
    } catch (NacosException e) {
        //todo 提醒:异常自行处理此处省略
    }
}
 
Example 3
Source File: NacosConfigIniter.java    From jboot with Apache License 2.0 6 votes vote down vote up
public void initListener(ConfigService configService, NacosServerConfig config) {
    try {
        configService.addListener(config.getDataId(), config.getGroup()
                , new Listener() {
                    @Override
                    public Executor getExecutor() {
                        return null;
                    }

                    @Override
                    public void receiveConfigInfo(String configInfo) {
                        manager.doReceiveConfigInfo(configManager, configInfo);
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 4
Source File: FlinkNacosTest2.java    From flink-learning with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));
    env.setParallelism(1);

    String serverAddr = "localhost";
    String dataId = "test";
    String group = "DEFAULT_GROUP";
    Properties properties = new Properties();
    properties.put("serverAddr", serverAddr);
    ConfigService configService = NacosFactory.createConfigService(properties);
    final String[] content = {configService.getConfig(dataId, group, 5000)};
    configService.addListener(dataId, group, new Listener() {
        @Override
        public Executor getExecutor() {
            return null;
        }

        @Override
        public void receiveConfigInfo(String configInfo) {
            System.out.println("===============");
            content[0] = configInfo;
            env.getCheckpointConfig().setCheckpointInterval(Long.valueOf(content[0]));
            System.out.println("----------");
            System.out.println(env.getCheckpointConfig().getCheckpointInterval());
        }
    });
    System.out.println(content[0]);

    env.getCheckpointConfig().setCheckpointInterval(Long.valueOf(content[0]));
    env.getCheckpointConfig().setCheckpointTimeout(1000);
    env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
    env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.DELETE_ON_CANCELLATION);

    env.addSource(new SourceFunction<Tuple2<String, Long>>() {
        @Override
        public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
            while (true) {
                ctx.collect(new Tuple2<>("zhisheng", System.currentTimeMillis()));
                Thread.sleep(800);
            }
        }

        @Override
        public void cancel() {

        }
    }).print();


    env.execute();
}
 
Example 5
Source File: FlinkNacosTest2.java    From flink-learning with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.getConfig().setGlobalJobParameters(ParameterTool.fromArgs(args));
    env.setParallelism(1);

    String serverAddr = "localhost";
    String dataId = "test";
    String group = "DEFAULT_GROUP";
    Properties properties = new Properties();
    properties.put("serverAddr", serverAddr);
    ConfigService configService = NacosFactory.createConfigService(properties);
    final String[] content = {configService.getConfig(dataId, group, 5000)};
    configService.addListener(dataId, group, new Listener() {
        @Override
        public Executor getExecutor() {
            return null;
        }

        @Override
        public void receiveConfigInfo(String configInfo) {
            System.out.println("===============");
            content[0] = configInfo;
            env.getCheckpointConfig().setCheckpointInterval(Long.valueOf(content[0]));
            System.out.println("----------");
            System.out.println(env.getCheckpointConfig().getCheckpointInterval());
        }
    });
    System.out.println(content[0]);

    env.getCheckpointConfig().setCheckpointInterval(Long.valueOf(content[0]));
    env.getCheckpointConfig().setCheckpointTimeout(1000);
    env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
    env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.DELETE_ON_CANCELLATION);

    env.addSource(new SourceFunction<Tuple2<String, Long>>() {
        @Override
        public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
            while (true) {
                ctx.collect(new Tuple2<>("zhisheng", System.currentTimeMillis()));
                Thread.sleep(800);
            }
        }

        @Override
        public void cancel() {

        }
    }).print();


    env.execute();
}
 
Example 6
Source File: NacosConfigListenerMethodProcessor.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
@Override
protected void processListenerMethod(String beanName, final Object bean,
		Class<?> beanClass, final NacosConfigListener listener, final Method method,
		ApplicationContext applicationContext) {

	final String dataId = NacosUtils.readFromEnvironment(listener.dataId(),
			environment);
	final String groupId = NacosUtils.readFromEnvironment(listener.groupId(),
			environment);
	final String type = StringUtils.isEmpty(NacosUtils.readTypeFromDataId(dataId))
			? listener.type().getType()
			: NacosUtils.readTypeFromDataId(dataId);
	long timeout = listener.timeout();

	Assert.isTrue(StringUtils.hasText(dataId), "dataId must have content");
	Assert.isTrue(StringUtils.hasText(groupId), "groupId must have content");
	Assert.isTrue(timeout > 0, "timeout must be greater than zero");

	ConfigService configService = configServiceBeanBuilder
			.build(listener.properties());

	try {
		configService.addListener(dataId, groupId,
				new TimeoutNacosConfigListener(dataId, groupId, timeout) {

					@Override
					protected void onReceived(String config) {
						Class<?> targetType = method.getParameterTypes()[0];
						NacosConfigConverter configConverter = determineNacosConfigConverter(
								targetType, listener, type);
						Object parameterValue = configConverter.convert(config);
						// Execute target method
						ReflectionUtils.invokeMethod(method, bean, parameterValue);
					}
				});
	}
	catch (NacosException e) {
		logger.error("ConfigService can't add Listener for dataId : " + dataId
				+ " , groupId : " + groupId, e);
	}

	publishMetadataEvent(beanName, bean, beanClass, dataId, groupId, listener,
			method);

}
 
Example 7
Source File: NacosConfigurationPropertiesBinder.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
protected void bind(final Object bean, final String beanName,
		final NacosConfigurationProperties properties) {

	Assert.notNull(bean, "Bean must not be null!");

	Assert.notNull(properties, "NacosConfigurationProperties must not be null!");

	// support read data-id and group-id from spring environment
	final String dataId = NacosUtils.readFromEnvironment(properties.dataId(),
			environment);
	final String groupId = NacosUtils.readFromEnvironment(properties.groupId(),
			environment);
	String fileType = NacosUtils.readTypeFromDataId(dataId);
	final String type = StringUtils.isEmpty(fileType)
			? (properties.yaml() ? ConfigType.YAML.getType()
					: properties.type().getType())
			: fileType;

	final ConfigService configService = configServiceBeanBuilder
			.build(properties.properties());

	// Add a Listener if auto-refreshed
	if (properties.autoRefreshed()) {

		Listener listener = new AbstractListener() {
			@Override
			public void receiveConfigInfo(String config) {
				doBind(bean, beanName, dataId, groupId, type, properties, config,
						configService);
			}
		};
		try {//
			if (configService instanceof EventPublishingConfigService) {
				((EventPublishingConfigService) configService).addListener(dataId,
						groupId, type, listener);
			}
			else {
				configService.addListener(dataId, groupId, listener);
			}
		}
		catch (NacosException e) {
			if (logger.isErrorEnabled()) {
				logger.error(e.getMessage(), e);
			}
		}
	}

	String content = getContent(configService, dataId, groupId);

	if (hasText(content)) {
		doBind(bean, beanName, dataId, groupId, type, properties, content,
				configService);
	}
}
 
Example 8
Source File: NacosPropertySourcePostProcessor.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
public static void addListenerIfAutoRefreshed(
		final NacosPropertySource nacosPropertySource, final Properties properties,
		final ConfigurableEnvironment environment) {

	if (!nacosPropertySource.isAutoRefreshed()) { // Disable Auto-Refreshed
		return;
	}

	final String dataId = nacosPropertySource.getDataId();
	final String groupId = nacosPropertySource.getGroupId();
	final String type = nacosPropertySource.getType();
	final NacosServiceFactory nacosServiceFactory = getNacosServiceFactoryBean(
			beanFactory);

	try {

		ConfigService configService = nacosServiceFactory
				.createConfigService(properties);

		Listener listener = new AbstractListener() {

			@Override
			public void receiveConfigInfo(String config) {
				String name = nacosPropertySource.getName();
				NacosPropertySource newNacosPropertySource = new NacosPropertySource(
						dataId, groupId, name, config, type);
				newNacosPropertySource.copy(nacosPropertySource);
				MutablePropertySources propertySources = environment
						.getPropertySources();
				// replace NacosPropertySource
				propertySources.replace(name, newNacosPropertySource);
			}
		};

		if (configService instanceof EventPublishingConfigService) {
			((EventPublishingConfigService) configService).addListener(dataId,
					groupId, type, listener);
		}
		else {
			configService.addListener(dataId, groupId, listener);
		}

	}
	catch (NacosException e) {
		throw new RuntimeException(
				"ConfigService can't add Listener with properties : " + properties,
				e);
	}
}