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

The following examples show how to use com.alibaba.nacos.api.config.ConfigService. 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
@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 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
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 4
Source Project: api-boot   Source File: NacosRateLimiterConfigCentre.java    License: 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 5
Source Project: soul   Source File: NacosConfiguration.java    License: 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 6
/**
 * 监听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 7
Source Project: Sentinel   Source File: NacosConfigSender.java    License: 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 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: dubbo-samples   Source File: NacosUtils.java    License: 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 10
@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 11
@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 12
@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 13
Source Project: spring-cloud-alibaba   Source File: NacosConfigManager.java    License: 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 14
Source Project: jboot   Source File: NacosConfigIniter.java    License: 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 15
/**
 * 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 16
Source Project: soul   Source File: NacosCacheHandler.java    License: 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 17
Source Project: soul   Source File: NacosSyncDataConfiguration.java    License: 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 18
Source Project: dubbo-samples   Source File: NacosUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void writeAppRule() throws Throwable {
    String serverAddr = System.getProperty("nacos.address", "localhost");
    String dataId = "governance-conditionrouter-consumer.condition-router";
    String group = "dubbo";
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
    ConfigService configService = NacosFactory.createConfigService(properties);

    try (InputStream is = NacosUtils.class.getClassLoader().getResourceAsStream("dubbo-routers-condition.yml")) {
        String content = IOUtils.toString(is);
        if (configService.publishConfig(dataId, group, content)) {
            System.out.println("write " + dataId + ":" + group + " successfully.");
        }
    }
}
 
Example 19
private ConfigService resolveConfigService(Properties nacosProperties,
		ApplicationContext applicationContext) throws BeansException {

	ConfigService configService = null;

	try {
		configService = nacosServiceFactory.createConfigService(nacosProperties);
	}
	catch (NacosException e) {
		throw new BeanCreationException(e.getErrMsg(), e);
	}

	return configService;
}
 
Example 20
protected void doBind(Object bean, String beanName, String dataId, String groupId,
		String type, NacosConfigurationProperties properties, String content,
		ConfigService configService) {
	final String prefix = properties.prefix();
	PropertyValues propertyValues = NacosUtils.resolvePropertyValues(bean, prefix,
			dataId, groupId, content, type);
	doBind(bean, properties, propertyValues);
	publishBoundEvent(bean, beanName, dataId, groupId, properties, content,
			configService);
	publishMetadataEvent(bean, beanName, dataId, groupId, properties);
}
 
Example 21
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
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 23
/**
 * @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 24
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 25
@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 26
Source Project: nacos-spring-project   Source File: NacosUtils.java    License: 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 27
@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
@Test
public void testCreateConfigService() throws NacosException {
	ConfigService configService = nacosServiceFactory.createConfigService(properties);
	ConfigService configService2 = nacosServiceFactory
			.createConfigService(properties);
	Assert.assertTrue(configService == configService2);
}
 
Example 29
@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 30
public NacosConfigLoader(NacosConfigProperties nacosConfigProperties,
		ConfigurableEnvironment environment,
		Function<Properties, ConfigService> builder) {
	this.nacosConfigProperties = nacosConfigProperties;
	this.environment = environment;
	this.builder = builder;
}