com.alibaba.nacos.api.config.listener.Listener Java Examples

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

            @Override
            public void receiveConfigInfo(String configInfo) {
                publisher.publishEvent(new RefreshRoutesEvent(this));
            }
        });
    } catch (NacosException e) {
        log.error("nacos-addListener-error", e);
    }
}
 
Example #2
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 #3
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 #4
Source File: TimeoutNacosConfigListenerTest.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
private String receiveConfig(final long executionTime, long timeout, String content)
		throws NacosException {

	final AtomicReference<String> contentHolder = new AtomicReference<String>();

	Listener listener = new TimeoutNacosConfigListener(DATA_ID, GROUP_ID, timeout) {
		@Override
		protected void onReceived(String config) {
			doWait(executionTime);
			contentHolder.set(config);
			System.out.printf("[%s] %s \n", Thread.currentThread().getName(), config);
		}
	};

	configService.addListener(DATA_ID, GROUP_ID, listener);

	configService.publishConfig(DATA_ID, GROUP_ID, content);

	return contentHolder.get();
}
 
Example #5
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 #6
Source File: NacosEventListenerConfiguration.java    From nacos-spring-project with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() throws NacosException {
	// for NacosConfigReceivedEvent
	configService.publishConfig(DATA_ID, DEFAULT_GROUP, "Hello,World");

	// for NacosConfigRemovedEvent
	configService.removeConfig(DATA_ID, DEFAULT_GROUP);

	Listener listener = new AbstractListener() {
		@Override
		public void receiveConfigInfo(String configInfo) {
		}
	};

	// for NacosConfigListenerRegisteredEvent(true)
	configService.addListener(DATAID, DEFAULT_GROUP, listener);

	// for NacosConfigListenerRegisteredEvent(false)
	configService.removeListener(DATAID, DEFAULT_GROUP, listener);
}
 
Example #7
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 #8
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 #9
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 #10
Source File: AbstractNacosConfigService.java    From nacos-tutorial with Apache License 2.0 6 votes vote down vote up
public AbstractNacosConfigService(String serverAddress, String dataId, String group) {
    this.unitMap = new ConcurrentHashMap<>();
    this.configMap = new ConcurrentHashMap<>();
    // 刷新 unit
    this.refreshUnit();
    this.dataId = dataId;
    this.group = group;
    Properties properties = new Properties();
    properties.put("serverAddr", serverAddress);
    try {
        this.configService = NacosFactory.createConfigService(properties);
        // 增加监听器
        Listener listener = new ConfigListener();
        this.configService.addListener(dataId, group, listener);
    } catch (NacosException e) {
        e.printStackTrace();
    }
}
 
Example #11
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 #12
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatch() throws NacosException {
    final String expectValue = "expectValue";
    final String[] actualValue = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(expectValue))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> actualValue[0] = dataChangedEvent.getValue();
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualValue[0], is(expectValue));
}
 
Example #13
Source File: NacosContextRefresher.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void registerNacosListener(final String groupKey, final String dataKey) {
	String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
	Listener listener = listenerMap.computeIfAbsent(key,
			lst -> new AbstractSharedListener() {
				@Override
				public void innerReceive(String dataId, String group,
						String configInfo) {
					refreshCountIncrement();
					nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
					// todo feature: support single refresh for listening
					applicationContext.publishEvent(
							new RefreshEvent(this, null, "Refresh Nacos config"));
					if (log.isDebugEnabled()) {
						log.debug(String.format(
								"Refresh Nacos config group=%s,dataId=%s,configInfo=%s",
								group, dataId, configInfo));
					}
				}
			});
	try {
		configService.addListener(dataKey, groupKey, listener);
	}
	catch (NacosException e) {
		log.warn(String.format(
				"register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey,
				groupKey), e);
	}
}
 
Example #14
Source File: Application.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public void run(ApplicationArguments args) throws Exception {
	System.out.println(
			String.format("Initial username=%s, userAge=%d", userName, userAge));

	nacosConfigManager.getConfigService().addListener(
			"nacos-config-example.properties", "DEFAULT_GROUP", new Listener() {

				/**
				 * Callback with latest config data.
				 *
				 * For example, config data in Nacos is:
				 *
				 * user.name=Nacos user.age=25
				 * @param configInfo latest config data for specific dataId in Nacos
				 * server
				 */
				@Override
				public void receiveConfigInfo(String configInfo) {
					Properties properties = new Properties();
					try {
						properties.load(new StringReader(configInfo));
					}
					catch (IOException e) {
						e.printStackTrace();
					}
					System.out.println("config changed: " + properties);
				}

				@Override
				public Executor getExecutor() {
					return null;
				}
			});
}
 
Example #15
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 #16
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertWatchDeletedChangedType() throws NacosException {
    final ChangedType[] actualType = {null};
    doAnswer(AdditionalAnswers.answerVoid(getListenerAnswer(null))).when(configService).addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> actualType[0] = dataChangedEvent.getChangedType();
    REPOSITORY.watch("/sharding/test", listener);
    assertThat(actualType[0], is(ChangedType.UPDATED));
}
 
Example #17
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 #18
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows
@Test
public void assertWatchWhenThrowException() {
    final ChangedType[] actualType = {null};
    doThrow(NacosException.class)
            .when(configService)
            .addListener(anyString(), anyString(), any(Listener.class));
    DataChangedEventListener listener = dataChangedEvent -> actualType[0] = dataChangedEvent.getChangedType();
    REPOSITORY.watch("/sharding/test", listener);
    assertNull(actualType[0]);
}
 
Example #19
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 #20
Source File: EventPublishingConfigService.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs,
		Listener listener) throws NacosException {
	Listener listenerAdapter = new DelegatingEventPublishingListener(configService,
			dataId, group, applicationEventPublisher, executor, listener);
	return configService.getConfigAndSignListener(dataId, group, timeoutMs,
			listenerAdapter);
}
 
Example #21
Source File: NacosUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public String config(String data){
	try{
		Listener listener = null;
		return config(null, data, listener);
	}catch(Exception e){
		e.printStackTrace();
	}
	return null;
}
 
Example #22
Source File: NacosUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
public String config(String group, String data){
	try{
		Listener listener = null;
		return config(group, data, listener);
	}catch(Exception e){
		e.printStackTrace();
	}
	return null;
}
 
Example #23
Source File: DelegatingEventPublishingListener.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
DelegatingEventPublishingListener(ConfigService configService, String dataId,
		String groupId, String configType,
		ApplicationEventPublisher applicationEventPublisher, Executor executor,
		Listener delegate) {
	this.configService = configService;
	this.dataId = dataId;
	this.groupId = groupId;
	this.configType = configType;
	this.applicationEventPublisher = applicationEventPublisher;
	this.executor = executor;
	this.delegate = delegate;
}
 
Example #24
Source File: NacosDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param properties properties for construct {@link ConfigService} using {@link NacosFactory#createConfigService(Properties)}
 * @param groupId    group ID, cannot be empty
 * @param dataId     data ID, cannot be empty
 * @param parser     customized data parser, cannot be empty
 */
public NacosDataSource(final Properties properties, final String groupId, final String dataId,
                       Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: groupId=[%s], dataId=[%s]",
            groupId, dataId));
    }
    AssertUtil.notNull(properties, "Nacos properties must not be null, you could put some keys from PropertyKeyConst");
    this.groupId = groupId;
    this.dataId = dataId;
    this.properties = properties;
    this.configListener = new Listener() {
        @Override
        public Executor getExecutor() {
            return pool;
        }

        @Override
        public void receiveConfigInfo(final String configInfo) {
            RecordLog.info(String.format("[NacosDataSource] New property value received for (properties: %s) (dataId: %s, groupId: %s): %s",
                properties, dataId, groupId, configInfo));
            T newValue = NacosDataSource.this.parser.convert(configInfo);
            // Update the new value to the property.
            getProperty().updateValue(newValue);
        }
    };
    initNacosListener();
    loadInitialConfig();
}
 
Example #25
Source File: NacosCacheHandler.java    From soul with Apache License 2.0 5 votes vote down vote up
protected void watcherData(final String dataId, final OnChange oc) {
    Listener listener = new Listener() {
        @Override
        public void receiveConfigInfo(final String configInfo) {
            oc.change(configInfo);
        }
        
        @Override
        public Executor getExecutor() {
            return null;
        }
    };
    oc.change(getConfigAndSignListener(dataId, listener));
    LISTENERS.getOrDefault(dataId, new ArrayList<>()).add(listener);
}
 
Example #26
Source File: NacosDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param properties properties for construct {@link ConfigService} using {@link NacosFactory#createConfigService(Properties)}
 * @param groupId    group ID, cannot be empty
 * @param dataId     data ID, cannot be empty
 * @param parser     customized data parser, cannot be empty
 */
public NacosDataSource(final Properties properties, final String groupId, final String dataId,
                       Converter<String, T> parser) {
    super(parser);
    if (StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) {
        throw new IllegalArgumentException(String.format("Bad argument: groupId=[%s], dataId=[%s]",
            groupId, dataId));
    }
    AssertUtil.notNull(properties, "Nacos properties must not be null, you could put some keys from PropertyKeyConst");
    this.groupId = groupId;
    this.dataId = dataId;
    this.properties = properties;
    this.configListener = new Listener() {
        @Override
        public Executor getExecutor() {
            return pool;
        }

        @Override
        public void receiveConfigInfo(final String configInfo) {
            RecordLog.info(String.format("[NacosDataSource] New property value received for (properties: %s) (dataId: %s, groupId: %s): %s",
                properties, dataId, groupId, configInfo));
            T newValue = NacosDataSource.this.parser.convert(configInfo);
            // Update the new value to the property.
            getProperty().updateValue(newValue);
        }
    };
    initNacosListener();
    loadInitialConfig();
}
 
Example #27
Source File: MockConfigService.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
@Override
public void removeListener(String dataId, String group, Listener listener) {
	String key = createKey(dataId, group);
	listenersCache.remove(key);
}
 
Example #28
Source File: NacosCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private VoidAnswer3 getListenerAnswer(final String expectValue) {
    return (VoidAnswer3<String, String, Listener>) (dataId, group, listener) -> listener.receiveConfigInfo(expectValue);
}
 
Example #29
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 #30
Source File: NacosCacheHandler.java    From soul with Apache License 2.0 4 votes vote down vote up
@SneakyThrows
private String getConfigAndSignListener(final String dataId, final Listener listener) {
    return configService.getConfigAndSignListener(dataId, GROUP, 6000, listener);
}