com.alibaba.nacos.api.config.ConfigService Java Examples

The following examples show how to use com.alibaba.nacos.api.config.ConfigService. 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: NacosConfigHealthIndicator.java    From nacos-spring-boot-project with Apache License 2.0 7 votes vote down vote up
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
	builder.up();
	NacosServiceFactory nacosServiceFactory = CacheableEventPublishingNacosServiceFactory
			.getSingleton();
	for (ConfigService configService : nacosServiceFactory.getConfigServices()) {
		if (configService instanceof NacosServiceMetaData) {
			NacosServiceMetaData nacosServiceMetaData = (NacosServiceMetaData) configService;
			Properties properties = nacosServiceMetaData.getProperties();
			builder.withDetail(
					JSON.toJSONString(
							PropertiesUtils.extractSafeProperties(properties)),
					configService.getServerStatus());
		}
		if (!configService.getServerStatus().toLowerCase().equals(UP_STATUS)) {
			builder.down();
		}
	}
}
 
Example #2
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 #3
Source File: NacosBootConfigurationPropertiesBinder.java    From nacos-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@Override
protected void doBind(Object bean, String beanName, String dataId, String groupId,
		String configType, NacosConfigurationProperties properties, String content,
		ConfigService configService) {
	String name = "nacos-bootstrap-" + beanName;
	NacosPropertySource propertySource = new NacosPropertySource(name, dataId,
			groupId, content, configType);
	environment.getPropertySources().addLast(propertySource);
	Binder binder = Binder.get(environment);
	ResolvableType type = getBeanType(bean, beanName);
	Bindable<?> target = Bindable.of(type).withExistingValue(bean);
	binder.bind(properties.prefix(), target);
	publishBoundEvent(bean, beanName, dataId, groupId, properties, content,
			configService);
	publishMetadataEvent(bean, beanName, dataId, groupId, properties);
	environment.getPropertySources().remove(name);
}
 
Example #4
Source File: NacosUtils.java    From dubbo-samples with Apache License 2.0 6 votes vote down vote up
public static void writeDubboProperties() throws Throwable {
    String serverAddr = System.getProperty("nacos.address", "localhost");
    String dataId = "dubbo.properties";
    String group = "dubbo";
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
    ConfigService configService = NacosFactory.createConfigService(properties);

    StringBuilder content = new StringBuilder();
    File file = new File(NacosUtils.class.getClassLoader().getResource("config-center.properties").getFile());
    try (FileReader reader = new FileReader(file)) {
        BufferedReader br = new BufferedReader(reader);
        String line;
        while ((line = br.readLine()) != null) {
            if (line.startsWith("dubbo.registry.address=")) {
                line = "dubbo.registry.address=nacos://" + serverAddr + ":8848";
            }
            content.append(line).append("\n");
        }
    }

    if (configService.publishConfig(dataId, group, content.toString())) {
        System.out.println("write " + dataId + ":" + group + " successfully.");
    }
}
 
Example #5
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 #6
Source File: NacosConfigSender.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String remoteAddress = "localhost";
    final String groupId = "Sentinel:Demo";
    final String dataId = "com.alibaba.csp.sentinel.demo.flow.rule";
    final String rule = "[\n"
        + "  {\n"
        + "    \"resource\": \"TestResource\",\n"
        + "    \"controlBehavior\": 0,\n"
        + "    \"count\": 5.0,\n"
        + "    \"grade\": 1,\n"
        + "    \"limitApp\": \"default\",\n"
        + "    \"strategy\": 0\n"
        + "  }\n"
        + "]";
    ConfigService configService = NacosFactory.createConfigService(remoteAddress);
    System.out.println(configService.publishConfig(dataId, groupId, rule));
}
 
Example #7
Source File: NacosConfigManager.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
/**
 * Compatible with old design,It will be perfected in the future.
 */
static ConfigService createConfigService(
		NacosConfigProperties nacosConfigProperties) {
	if (Objects.isNull(service)) {
		synchronized (NacosConfigManager.class) {
			try {
				if (Objects.isNull(service)) {
					service = NacosFactory.createConfigService(
							nacosConfigProperties.assembleConfigServiceProperties());
				}
			}
			catch (NacosException e) {
				log.error(e.getMessage());
				throw new NacosConnectionFailureException(
						nacosConfigProperties.getServerAddr(), e.getMessage(), e);
			}
		}
	}
	return service;
}
 
Example #8
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 #9
Source File: NacosConfiguration.java    From soul with Apache License 2.0 6 votes vote down vote up
/**
 * register configService in spring ioc.
 *
 * @param nacosConfig the nacos configuration
 * @return ConfigService {@linkplain ConfigService}
 * @throws Exception the exception
 */
@Bean
public ConfigService nacosConfigService(final NacosConfig nacosConfig) throws Exception {
    Properties properties = new Properties();
    if (nacosConfig.getAcm() != null && nacosConfig.getAcm().isEnabled()) {
        //使用阿里云ACM服务
        properties.put(PropertyKeyConst.ENDPOINT, nacosConfig.getAcm().getEndpoint());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfig.getAcm().getNamespace());
        //使用子账户ACM管理权限
        properties.put(PropertyKeyConst.ACCESS_KEY, nacosConfig.getAcm().getAccessKey());
        properties.put(PropertyKeyConst.SECRET_KEY, nacosConfig.getAcm().getSecretKey());
    } else {
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosConfig.getUrl());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
    }
    return NacosFactory.createConfigService(properties);
}
 
Example #10
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 #11
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 #12
Source File: NacosRateLimiterConfigCentre.java    From api-boot with Apache License 2.0 6 votes vote down vote up
public NacosRateLimiterConfigCentre(ConfigService configService) {
    this.configService = configService;

    // check configService not null
    Assert.notNull(configService, "ConfigService is required.");

    // load config data from nacos
    String configData = loadConfigData();

    // convert config data to properties
    this.configProperties = toProperties(configData);
    logger.info("ApiBoot RateLimiter nacos config properties load complete.");

    // Enable monitoring of receiving configuration changes
    addConfigChangeListener();
}
 
Example #13
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 #14
Source File: NacosConfigSender.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final String remoteAddress = "localhost";
    final String groupId = "Sentinel:Demo";
    final String dataId = "com.alibaba.csp.sentinel.demo.flow.rule";
    final String rule = "[\n"
        + "  {\n"
        + "    \"resource\": \"TestResource\",\n"
        + "    \"controlBehavior\": 0,\n"
        + "    \"count\": 5.0,\n"
        + "    \"grade\": 1,\n"
        + "    \"limitApp\": \"default\",\n"
        + "    \"strategy\": 0\n"
        + "  }\n"
        + "]";
    ConfigService configService = NacosFactory.createConfigService(remoteAddress);
    System.out.println(configService.publishConfig(dataId, groupId, rule));
}
 
Example #15
Source File: NacosSyncDataConfiguration.java    From soul with Apache License 2.0 5 votes vote down vote up
/**
 * Nacos config service config service.
 *
 * @param nacosConfig the nacos config
 * @return the config service
 * @throws Exception the exception
 */
@Bean
public ConfigService nacosConfigService(final NacosConfig nacosConfig) throws Exception {
    Properties properties = new Properties();
    if (nacosConfig.getAcm() != null && nacosConfig.getAcm().isEnabled()) {
        properties.put(PropertyKeyConst.ENDPOINT, nacosConfig.getAcm().getEndpoint());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfig.getAcm().getNamespace());
        properties.put(PropertyKeyConst.ACCESS_KEY, nacosConfig.getAcm().getAccessKey());
        properties.put(PropertyKeyConst.SECRET_KEY, nacosConfig.getAcm().getSecretKey());
    } else {
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosConfig.getUrl());
        properties.put(PropertyKeyConst.NAMESPACE, nacosConfig.getNamespace());
    }
    return NacosFactory.createConfigService(properties);
}
 
Example #16
Source File: EventPublishingConfigService.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
public EventPublishingConfigService(ConfigService configService,
		Properties properties, ConfigurableApplicationContext context,
		Executor executor) {
	this.configService = configService;
	this.properties = properties;
	this.applicationEventPublisher = new DeferredApplicationEventPublisher(context);
	this.executor = executor;
}
 
Example #17
Source File: NacosPropertySourceLocator.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public PropertySource<?> locate(Environment env) {
	nacosConfigProperties.setEnvironment(env);
	ConfigService configService = nacosConfigManager.getConfigService();

	if (null == configService) {
		log.warn("no instance of config service found, can't load config from nacos");
		return null;
	}
	long timeout = nacosConfigProperties.getTimeout();
	nacosPropertySourceBuilder = new NacosPropertySourceBuilder(configService,
			timeout);
	String name = nacosConfigProperties.getName();

	String dataIdPrefix = nacosConfigProperties.getPrefix();
	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = name;
	}

	if (StringUtils.isEmpty(dataIdPrefix)) {
		dataIdPrefix = env.getProperty("spring.application.name");
	}

	CompositePropertySource composite = new CompositePropertySource(
			NACOS_PROPERTY_SOURCE_NAME);

	loadSharedConfiguration(composite);
	loadExtConfiguration(composite);
	loadApplicationConfiguration(composite, dataIdPrefix, nacosConfigProperties, env);

	return composite;
}
 
Example #18
Source File: ApiBootRateLimiterNacosConfigConfiguration.java    From api-boot with Apache License 2.0 5 votes vote down vote up
/**
 * init ConfigService Instance
 *
 * @return NacosConfigService
 * @throws NacosException Nacos Exception
 */
@Bean
@ConditionalOnMissingBean(name = NACOS_CONFIG_SERVICE_NAME)
public ConfigService nacosConfigService() throws NacosException {
    Properties properties = new Properties();
    properties.put(SERVER_ADDR, Objects.toString(nacosConfigProperties.getServerAddr(), ""));
    properties.put(ENCODE, Objects.toString(nacosConfigProperties.getEncode(), ""));
    properties.put(NAMESPACE, Objects.toString(nacosConfigProperties.getNamespace(), ""));
    properties.put(ACCESS_KEY, Objects.toString(nacosConfigProperties.getAccessKey(), ""));
    properties.put(SECRET_KEY, Objects.toString(nacosConfigProperties.getSecretKey(), ""));
    properties.put(CONTEXT_PATH, Objects.toString(nacosConfigProperties.getContextPath(), ""));
    properties.put(ENDPOINT, Objects.toString(nacosConfigProperties.getEndpoint(), ""));
    return NacosFactory.createConfigService(properties);
}
 
Example #19
Source File: NacosConfigManager.java    From jboot with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化 nacos 配置监听
 */
public void init(JbootConfigManager configManager) {

    NacosServerConfig nacosServerConfig = configManager.get(NacosServerConfig.class);
    if (!nacosServerConfig.isEnable() || !nacosServerConfig.isConfigOk()) {
        return;
    }

    try {

        ConfigService configService = NacosFactory.createConfigService(nacosServerConfig.toProperties());
        String content = configService.getConfig(nacosServerConfig.getDataId()
                , nacosServerConfig.getGroup(), 3000);

        if (StrUtil.isNotBlank(content)) {
            contentProperties = str2Properties(content);
            if (contentProperties != null) {
                configManager.setRemoteProperties(contentProperties);
            }
        }

        new NacosConfigIniter(this, configManager).initListener(configService, nacosServerConfig);

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #20
Source File: NacosCacheHandler.java    From soul with Apache License 2.0 5 votes vote down vote up
public NacosCacheHandler(final ConfigService configService, final PluginDataSubscriber pluginDataSubscriber,
                         final List<MetaDataSubscriber> metaDataSubscribers,
                         final List<AuthDataSubscriber> authDataSubscribers) {
    this.configService = configService;
    this.pluginDataSubscriber = pluginDataSubscriber;
    this.metaDataSubscribers = metaDataSubscribers;
    this.authDataSubscribers = authDataSubscribers;
}
 
Example #21
Source File: NacosConfigurationPropertiesBinder.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
protected void publishBoundEvent(Object bean, String beanName, String dataId,
		String groupId, NacosConfigurationProperties properties, String content,
		ConfigService configService) {
	NacosConfigEvent event = new NacosConfigurationPropertiesBeanBoundEvent(
			configService, dataId, groupId, bean, beanName, properties, content);
	applicationEventPublisher.publishEvent(event);
}
 
Example #22
Source File: NacosContextRefresher.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * recommend to use
 * {@link NacosContextRefresher#NacosContextRefresher(NacosConfigManager, NacosRefreshHistory)}.
 * @param refreshProperties refreshProperties
 * @param refreshHistory refreshHistory
 * @param configService configService
 */
@Deprecated
public NacosContextRefresher(NacosRefreshProperties refreshProperties,
		NacosRefreshHistory refreshHistory, ConfigService configService) {
	this.isRefreshEnabled = refreshProperties.isEnabled();
	this.nacosRefreshHistory = refreshHistory;
	this.configService = configService;
}
 
Example #23
Source File: NacosConfigLoader.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
public NacosConfigLoader(NacosConfigProperties nacosConfigProperties,
		ConfigurableEnvironment environment,
		Function<Properties, ConfigService> builder) {
	this.nacosConfigProperties = nacosConfigProperties;
	this.environment = environment;
	this.builder = builder;
}
 
Example #24
Source File: NacosUtils.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
/**
 * Get content from {@link ConfigService} via dataId and groupId
 *
 * @param configService {@link ConfigService}
 * @param dataId dataId
 * @param groupId groupId
 * @return If available , return content , or <code>null</code>
 */
public static String getContent(ConfigService configService, String dataId,
		String groupId) {
	String content = null;
	try {
		content = configService.getConfig(dataId, groupId, DEFAULT_TIMEOUT);
	}
	catch (NacosException e) {
		if (logger.isErrorEnabled()) {
			logger.error("Can't get content from dataId : " + dataId + " , groupId : "
					+ groupId, e);
		}
	}
	return content;
}
 
Example #25
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 #26
Source File: CacheableEventPublishingNacosServiceFactory.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public ConfigService createConfigService(Properties properties)
		throws NacosException {
	Properties copy = new Properties();
	copy.putAll(properties);
	return (ConfigService) createWorkerManager.get(ServiceType.CONFIG).run(copy,
			null);
}
 
Example #27
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 #28
Source File: CacheableEventPublishingNacosServiceFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetConfigServices() throws NacosException {
	ConfigService configService = nacosServiceFactory.createConfigService(properties);
	ConfigService configService2 = nacosServiceFactory
			.createConfigService(properties);
	Assert.assertTrue(configService == configService2);
	Assert.assertEquals(1, nacosServiceFactory.getConfigServices().size());
	Assert.assertEquals(configService,
			nacosServiceFactory.getConfigServices().iterator().next());
}
 
Example #29
Source File: NacosConfigurationPropertiesBeanBoundEvent.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
/**
 * @param configService Nacos {@link ConfigService}
 * @param dataId data ID
 * @param groupId group ID
 * @param bean annotated {@link NacosConfigurationProperties} bean
 * @param beanName the name of annotated {@link NacosConfigurationProperties} bean
 * @param properties {@link NacosConfigurationProperties} object
 * @param content the Nacos content for binding
 */
public NacosConfigurationPropertiesBeanBoundEvent(ConfigService configService,
		String dataId, String groupId, Object bean, String beanName,
		NacosConfigurationProperties properties, String content) {
	super(configService, dataId, groupId);
	this.bean = bean;
	this.beanName = beanName;
	this.properties = properties;
	this.content = content;
}
 
Example #30
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);
}