com.alibaba.nacos.api.PropertyKeyConst Java Examples

The following examples show how to use com.alibaba.nacos.api.PropertyKeyConst. 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: NacosDataSourceFactoryBean.java    From spring-cloud-alibaba with Apache License 2.0 6 votes vote down vote up
@Override
public NacosDataSource getObject() throws Exception {
	Properties properties = new Properties();
	if (!StringUtils.isEmpty(this.serverAddr)) {
		properties.setProperty(PropertyKeyConst.SERVER_ADDR, this.serverAddr);
	}
	else {
		properties.setProperty(PropertyKeyConst.ACCESS_KEY, this.accessKey);
		properties.setProperty(PropertyKeyConst.SECRET_KEY, this.secretKey);
		properties.setProperty(PropertyKeyConst.ENDPOINT, this.endpoint);
	}
	if (!StringUtils.isEmpty(this.namespace)) {
		properties.setProperty(PropertyKeyConst.NAMESPACE, this.namespace);
	}
	properties.setProperty(PropertyKeyConst.USERNAME, this.username);
	properties.setProperty(PropertyKeyConst.PASSWORD, this.password);
	return new NacosDataSource(properties, groupId, dataId, converter);
}
 
Example #3
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 #4
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 #5
Source File: NacosRegistryNamespaceTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithNamespace() {
    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol("nacos")
        .setSubscribe(true)
        .setAddress("127.0.0.1:8848/namespace")
        .setRegister(true);

    NacosRegistry registry = (NacosRegistry) RegistryFactory.getRegistry(registryConfig);
    registry.init();

    Properties properties = registry.getNacosConfig();

    String address = properties.getProperty(PropertyKeyConst.SERVER_ADDR);

    Assert.assertEquals("127.0.0.1:8848", address);
    String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
    Assert.assertEquals("namespace", namespace);

}
 
Example #6
Source File: NacosRegistryNamespaceTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithoutNamespace() {
    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol("nacos")
        .setSubscribe(true)
        .setAddress("127.0.0.1:8848/")
        .setRegister(true);

    NacosRegistry registry = (NacosRegistry) RegistryFactory.getRegistry(registryConfig);
    registry.init();

    Properties properties = registry.getNacosConfig();

    String address = properties.getProperty(PropertyKeyConst.SERVER_ADDR);

    Assert.assertEquals("127.0.0.1:8848", address);
    String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
    Assert.assertEquals("sofa-rpc", namespace);

}
 
Example #7
Source File: NacosRegistryNamespaceTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithoutSlashNamespace() {
    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol("nacos")
        .setSubscribe(true)
        .setAddress("127.0.0.1:8848")
        .setRegister(true);

    NacosRegistry registry = (NacosRegistry) RegistryFactory.getRegistry(registryConfig);
    registry.init();

    Properties properties = registry.getNacosConfig();

    String address = properties.getProperty(PropertyKeyConst.SERVER_ADDR);

    Assert.assertEquals("127.0.0.1:8848", address);
    String namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
    //default namespace
    Assert.assertEquals("sofa-rpc", namespace);

}
 
Example #8
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 #9
Source File: NacosCenterRepository.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize nacos instance.
 *
 * @param config config center configuration
 */
@Override
public void init(final CenterConfiguration config) {
    try {
        nacosProperties = new NacosProperties(props);
        Properties props = new Properties();
        props.put(PropertyKeyConst.SERVER_ADDR, config.getServerLists());
        props.put(PropertyKeyConst.NAMESPACE, null == config.getNamespace() ? "" : config.getNamespace());
        configService = NacosFactory.createConfigService(props);
    } catch (final NacosException ex) {
        log.error("Init nacos config center exception for: {}", ex.toString());
    }
}
 
Example #10
Source File: NacosDiscoveryAutoConfigurationTest.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testNacosGlobalProperties() {
	Properties properties = applicationContext.getBean(
			NacosBeanUtils.DISCOVERY_GLOBAL_NACOS_PROPERTIES_BEAN_NAME,
			Properties.class);
	Assert.assertEquals("localhost",
			properties.getProperty(PropertyKeyConst.SERVER_ADDR));
}
 
Example #11
Source File: NacosConfigAutoConfigurationTest.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@Test
public void testNacosGlobalProperties() {
	Properties properties = applicationContext.getBean(
			NacosBeanUtils.CONFIG_GLOBAL_NACOS_PROPERTIES_BEAN_NAME,
			Properties.class);
	Assert.assertEquals("localhost",
			properties.getProperty(PropertyKeyConst.SERVER_ADDR));
}
 
Example #12
Source File: PropertiesUtils.java    From nacos-spring-boot-project with Apache License 2.0 5 votes vote down vote up
public static Map<Object, Object> extractSafeProperties(Properties properties) {
	Map<Object, Object> result = new HashMap<>();
	properties.forEach((key, val) -> {
		if (!PropertyKeyConst.SECRET_KEY.equals(key)) {
			result.put(key, val);
		}
	});
	return result;
}
 
Example #13
Source File: TestConfiguration.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Bean(name = GLOBAL_NACOS_PROPERTIES_BEAN_NAME)
public Properties globalNacosProperties() {
	Properties properties = new Properties();
	if (!StringUtils.isEmpty(System.getProperty("server.addr"))) {
		properties.put(PropertyKeyConst.SERVER_ADDR,
				System.getProperty("server.addr"));
	}
	return properties;
}
 
Example #14
Source File: CacheableNacosInjectedFactoryTest.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	properties.setProperty(PropertyKeyConst.NAMESPACE, "nc");
	properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
	properties.setProperty(PropertyKeyConst.ACCESS_KEY, "a");
	properties.setProperty(PropertyKeyConst.SECRET_KEY, "s");

	properties2.setProperty(PropertyKeyConst.CLUSTER_NAME, "nc");
	properties2.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1");
	properties2.setProperty(PropertyKeyConst.ACCESS_KEY, "a");
	properties2.setProperty(PropertyKeyConst.SECRET_KEY, "s");
}
 
Example #15
Source File: GlobalNacosPropertiesBeanDefinitionParser.java    From nacos-spring-project with Apache License 2.0 5 votes vote down vote up
@Override
public BeanDefinition parse(Element element, ParserContext parserContext) {

	Properties properties = new Properties();

	Environment environment = parserContext.getDelegate().getReaderContext()
			.getReader().getEnvironment();

	properties.setProperty(PropertyKeyConst.ENDPOINT, element.getAttribute(ENDPOINT));
	properties.setProperty(PropertyKeyConst.NAMESPACE,
			element.getAttribute(NAMESPACE));
	properties.setProperty(PropertyKeyConst.ACCESS_KEY,
			element.getAttribute(ACCESS_KEY));
	properties.setProperty(PropertyKeyConst.SECRET_KEY,
			element.getAttribute(SECRET_KEY));
	properties.setProperty(PropertyKeyConst.SERVER_ADDR,
			element.getAttribute(SERVER_ADDR));
	properties.setProperty(PropertyKeyConst.CLUSTER_NAME,
			element.getAttribute(CLUSTER_NAME));
	properties.setProperty(PropertyKeyConst.ENCODE, element.getAttribute(ENCODE));
	properties.setProperty(PropertyKeyConst.USERNAME, element.getAttribute(USERNAME));
	properties.setProperty(PropertyKeyConst.PASSWORD, element.getAttribute(PASSWORD));

	BeanDefinitionRegistry registry = parserContext.getRegistry();

	// Register Global Nacos Properties as Spring singleton bean
	registerGlobalNacosProperties(properties, registry, environment,
			GLOBAL_NACOS_PROPERTIES_BEAN_NAME);

	return null;
}
 
Example #16
Source File: NacosUtils.java    From dubbo-samples with 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 #17
Source File: NacosRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void init() {
    if (namingService != null) {
        return;
    }

    String addressInput = registryConfig.getAddress(); // xxx:8848,yyy:8848/namespace
    if (StringUtils.isEmpty(addressInput)) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EMPTY_ADDRESS, EXT_NAME));
    }
    int idx = addressInput.indexOf(CONTEXT_SEP);
    String namespace;
    String address; // IP地址
    if (idx > 0) {
        address = addressInput.substring(0, idx);
        namespace = addressInput.substring(idx + 1);
        //for host:port/ this scene
        if (StringUtils.isBlank(namespace)) {
            namespace = DEFAULT_NAMESPACE;
        }
    } else {
        address = addressInput;
        namespace = DEFAULT_NAMESPACE;
    }

    defaultCluster = Collections.singletonList(NacosRegistryHelper.DEFAULT_CLUSTER);

    nacosConfig.put(PropertyKeyConst.SERVER_ADDR, address);
    nacosConfig.put(PropertyKeyConst.NAMESPACE, namespace);

    try {
        namingService = NamingFactory.createNamingService(nacosConfig);
    } catch (NacosException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_INIT_NACOS_NAMING_SERVICE, address), e);
    }
}
 
Example #18
Source File: NacosDataSourceDemo.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private static void loadMyNamespaceRules() {
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
    properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #19
Source File: NacosServerHolder.java    From nacos-sync with Apache License 2.0 5 votes vote down vote up
@Override
NamingService createServer(String clusterId, Supplier<String> serverAddressSupplier, String namespace) throws Exception {
    Properties properties = new Properties();
    properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddressSupplier.get());
    properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);
    return NamingFactory.createNamingService(properties);
}
 
Example #20
Source File: NacosNamingServiceUtils.java    From dubbo-registry-nacos with Apache License 2.0 5 votes vote down vote up
private static String[] initNacosPropertyNames() {
    return Stream.of(PropertyKeyConst.class.getFields())
            .filter(f -> isStatic(f.getModifiers()))         // static
            .filter(f -> isPublic(f.getModifiers()))         // public
            .filter(f -> isFinal(f.getModifiers()))          // final
            .filter(f -> String.class.equals(f.getType()))   // String type
            .map(NacosNamingServiceUtils::getConstantValue)
            .filter(Objects::nonNull)
            .map(String::valueOf)
            .toArray(String[]::new);
}
 
Example #21
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 #22
Source File: NacosDataSourceDemo.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private static void loadMyNamespaceRules() {
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
    properties.put(PropertyKeyConst.NAMESPACE, NACOS_NAMESPACE_ID);

    ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
            }));
    FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
}
 
Example #23
Source File: NacosDataSource.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private static Properties buildProperties(String serverAddr) {
    Properties properties = new Properties();
    properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
    return properties;
}
 
Example #24
Source File: CacheableEventPublishingNacosServiceFactoryTest.java    From nacos-spring-project with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
	properties.setProperty(PropertyKeyConst.SERVER_ADDR, "127.0.0.1");
}
 
Example #25
Source File: NacosPropertiesBuilder.java    From nacos-spring-boot-project with Apache License 2.0 4 votes vote down vote up
public static Properties buildNacosProperties(Environment environment,
		String serverAddr, String namespaceId, String endpoint, String secretKey,
		String accessKey, String ramRoleName, String configLongPollTimeout,
		String configRetryTimeout, String maxRetry, boolean enableRemoteSyncConfig,
		String username, String password) {
	Properties properties = new Properties();
	if (StringUtils.isNotEmpty(serverAddr)) {
		properties.put(PropertyKeyConst.SERVER_ADDR,
				environment.resolvePlaceholders(serverAddr));
	}
	if (StringUtils.isNotEmpty(namespaceId)) {
		properties.put(PropertyKeyConst.NAMESPACE,
				environment.resolvePlaceholders(namespaceId));
	}
	if (StringUtils.isNotEmpty(endpoint)) {
		properties.put(PropertyKeyConst.ENDPOINT,
				environment.resolvePlaceholders(endpoint));
	}
	if (StringUtils.isNotEmpty(secretKey)) {
		properties.put(PropertyKeyConst.SECRET_KEY,
				environment.resolvePlaceholders(secretKey));
	}
	if (StringUtils.isNotEmpty(accessKey)) {
		properties.put(PropertyKeyConst.ACCESS_KEY,
				environment.resolvePlaceholders(accessKey));
	}
	if (StringUtils.isNoneEmpty(ramRoleName)) {
		properties.put(PropertyKeyConst.RAM_ROLE_NAME,
				environment.resolvePlaceholders(ramRoleName));
	}
	if (StringUtils.isNotEmpty(configLongPollTimeout)) {
		properties.put(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT,
				environment.resolvePlaceholders(configLongPollTimeout));
	}
	if (StringUtils.isNotEmpty(configRetryTimeout)) {
		properties.put(PropertyKeyConst.CONFIG_RETRY_TIME,
				environment.resolvePlaceholders(configRetryTimeout));
	}
	if (StringUtils.isNotEmpty(maxRetry)) {
		properties.put(PropertyKeyConst.MAX_RETRY,
				environment.resolvePlaceholders(maxRetry));
	}
	if (StringUtils.isNotBlank(username)) {
		properties.put(PropertyKeyConst.USERNAME,
				environment.resolvePlaceholders(username));
	}
	if (StringUtils.isNotBlank(password)) {
		properties.put(PropertyKeyConst.PASSWORD,
				environment.resolvePlaceholders(password));
	}
	properties.put(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG,
			String.valueOf(enableRemoteSyncConfig));
	return properties;
}
 
Example #26
Source File: NacosDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private static Properties buildProperties(String serverAddr) {
    Properties properties = new Properties();
    properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
    return properties;
}