Java Code Examples for com.alibaba.nacos.api.NacosFactory

The following examples show how to use com.alibaba.nacos.api.NacosFactory. 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
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 2
Source Project: nacos-tutorial   Source File: AbstractNacosConfigService.java    License: 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 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: 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 5
/**
 * 监听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 6
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 7
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 8
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 9
@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 10
@Override
public NamingMaintainService run(Properties properties,
		NamingMaintainService service) throws NacosException {
	String cacheKey = identify(properties);
	NamingMaintainService namingMaintainService = maintainServiceCache
			.get(cacheKey);

	if (namingMaintainService == null) {
		if (service == null) {
			service = NacosFactory.createMaintainService(properties);
		}
		namingMaintainService = new DelegatingNamingMaintainService(service,
				properties);
		maintainServiceCache.put(cacheKey, namingMaintainService);
	}
	return namingMaintainService;
}
 
Example 11
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 12
Source Project: Moss   Source File: MultRegisterCenterServerMgmtConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public MultRegisterCenter initMultNacos() {
    URL_MAP.put("nacos1","127.0.0.1:8848");
    Map<String, NamingService> multEurekaMap = Maps.newConcurrentMap();
    Map<String, MossNacosAutoServiceRegistration> multRegistrationMap = Maps.newConcurrentMap();
    Map<NamingService, HeartbeatMonitor> multHeartbeatMonitorMap=new ConcurrentHashMap<NamingService, HeartbeatMonitor>();
    URL_MAP.entrySet().forEach(e -> {
        NacosDiscoveryProperties nacosDiscoveryProperties=new NacosDiscoveryProperties();
        nacosDiscoveryProperties.setService("halo-moss");
        nacosDiscoveryProperties.setServerAddr(e.getValue());
        try {
            NamingService namingService=NacosFactory.createNamingService(e.getValue());
            com.alibaba.nacos.api.naming.pojo.Instance instance = new com.alibaba.nacos.api.naming.pojo.Instance();
            instance.setIp(inetUtils.findFirstNonLoopbackHostInfo().getIpAddress());
            instance.setPort(-1);
            instance.setWeight(1);
            instance.setClusterName("DEFAULT");
            namingService.registerInstance("halo-moss", instance);
            this.context.publishEvent(
                    new InstanceRegisteredEvent<>(this, namingService));
            multEurekaMap.put(e.getKey(),namingService);
            multHeartbeatMonitorMap.put(namingService,new HeartbeatMonitor());
        } catch (NacosException e1) {
            e1.printStackTrace();
        }
        //NacosServiceRegistry serviceRegistry=new NacosServiceRegistry();
        //AutoServiceRegistrationProperties autoServiceRegistrationProperties=new AutoServiceRegistrationProperties();
        //MossNacosAutoServiceRegistration autoServiceRegistration = new MossNacosAutoServiceRegistration(serviceRegistry,autoServiceRegistrationProperties,registration,registration);
        //autoServiceRegistration.setRegistration(registration);
        //multRegistrationMap.put(e.getKey(), autoServiceRegistration);

    });
    multRegisterCenter = new MultRegisterCenter(multEurekaMap, multRegistrationMap,multHeartbeatMonitorMap);
    return multRegisterCenter;
}
 
Example 13
Source Project: Sentinel-Dashboard-Nacos   Source File: NacosDataSource.java    License: Apache License 2.0 5 votes vote down vote up
private void initNacosListener() {
    try {
        this.configService = NacosFactory.createConfigService(this.properties);
        // Add config listener.
        configService.addListener(dataId, groupId, configListener);
    } catch (Exception e) {
        RecordLog.warn("[NacosDataSource] Error occurred when initializing Nacos data source", e);
        e.printStackTrace();
    }
}
 
Example 14
/**
 * 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 15
Source Project: joyrpc   Source File: NacosRegistry.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doOpen() {
    try {
        namingService = NacosFactory.createNamingService(properties);
    } catch (NacosException e) {
        logger.error(e.getErrMsg(), e);
        throw new IllegalStateException(e);
    }
    super.doOpen();
}
 
Example 16
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 17
/**
 * Create an instance of {@link NamingService} from specified {@link URL connection url}
 *
 * @param connectionURL {@link URL connection url}
 * @return {@link NamingService}
 * @since 2.7.5
 */
public static NamingService createNamingService(URL connectionURL) {
    Properties nacosProperties = buildNacosProperties(connectionURL);
    NamingService namingService;
    try {
        namingService = NacosFactory.createNamingService(nacosProperties);
    } catch (NacosException e) {
        if (logger.isErrorEnabled()) {
            logger.error(e.getErrMsg(), e);
        }
        throw new IllegalStateException(e);
    }
    return namingService;
}
 
Example 18
Source Project: Sentinel   Source File: NacosDataSource.java    License: Apache License 2.0 5 votes vote down vote up
private void initNacosListener() {
    try {
        this.configService = NacosFactory.createConfigService(this.properties);
        // Add config listener.
        configService.addListener(dataId, groupId, configListener);
    } catch (Exception e) {
        RecordLog.warn("[NacosDataSource] Error occurred when initializing Nacos data source", e);
        e.printStackTrace();
    }
}
 
Example 19
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 20
@Override
public NamingService run(Properties properties, NamingService service)
		throws NacosException {
	String cacheKey = identify(properties);
	NamingService namingService = namingServicesCache.get(cacheKey);

	if (namingService == null) {
		if (service == null) {
			service = NacosFactory.createNamingService(properties);
		}
		namingService = new DelegatingNamingService(service, properties);
		namingServicesCache.put(cacheKey, namingService);
	}
	return namingService;
}
 
Example 21
Source Project: nacos-spring-project   Source File: NacosConfigLoader.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Load Nacos config vid dataId, groupId and {@link Properties acos Properties}
 *
 * @param dataId dataId
 * @param groupId groupId
 * @param nacosProperties {@link Properties acos Properties}
 * @return Nacos config
 * @throws RuntimeException If {@link ConfigService} creating is failed.
 */
public String load(String dataId, String groupId, Properties nacosProperties)
		throws RuntimeException {
	try {
		configService = nacosServiceFactory != null
				? nacosServiceFactory.createConfigService(nacosProperties)
				: NacosFactory.createConfigService(nacosProperties);
	}
	catch (NacosException e) {
		throw new RuntimeException("ConfigService can't be created with dataId :"
				+ dataId + " , groupId : " + groupId + " , properties : "
				+ nacosProperties, e);
	}
	return NacosUtils.getContent(configService, dataId, groupId);
}
 
Example 22
public NamingService namingServiceInstance() {

		if (null != namingService) {
			return namingService;
		}

		try {
			namingService = NacosFactory.createNamingService(getNacosProperties());
		}
		catch (Exception e) {
			log.error("create naming service error!properties={},e=,", this, e);
			return null;
		}
		return namingService;
	}
 
Example 23
Source Project: jboot   Source File: NacosConfigManager.java    License: 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 24
Source Project: shardingsphere   Source File: NacosCenterRepository.java    License: 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 25
Source Project: flink-learning   Source File: FlinkNacosTest2.java    License: 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 26
Source Project: flink-learning   Source File: FlinkNacosTest2.java    License: 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();
}