nacos篇一

1、配置文件

server.port=1027

#访问的根路径
server.servlet.context-path=/springboot-nacos
#Nacos服务名
spring.application.name=UserService
#nacos服务端的地址
nacos.config.server-addr=127.0.0.1:8848
#discovery地址
nacos.discovery.server-addr=127.0.0.1:8848

2、依赖包

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tx</groupId>
    <artifactId>springboot_nacos</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.alibaba.boot/nacos-config-spring-boot-starter -->
        <!--注意 spring boot 1.x的项目对应的是0.1.x spirng boot 2.x 对应0.2.x spring boot-->
        <!-- 1. nacos-配置管理功能依赖 -->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-config-spring-boot-starter</artifactId>
            <version>0.1.1</version>
        </dependency>
        <!--2. nacos-服务发现功能依赖-->
        <dependency>
            <groupId>com.alibaba.boot</groupId>
            <artifactId>nacos-discovery-spring-boot-starter</artifactId>
            <version>0.2.1</version>
        </dependency>
        <!--nacos的配置-->
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>

</project>


3、


//请求即可打印出来,即可拿到值。http://127.0.0.1:1027/springboot-nacos/config/get2
@Controller
@RequestMapping("config")
public class getvalue {

        @ResponseBody
        @RequestMapping("/get2")
        public Map getConfig() throws NacosException, InterruptedException {
            // 用以演示用,页面返回数据展示
            Map map = new HashMap();
            //  服务地址。本机演示故写localhost。请根据实际情况替换对应IP
            String serverAddr = "localhost";
            // 下面两个选项要和nacos里面新建的两个选项要一 一匹配
            String dataId = "nacos-spring";
            String group = "one-group";
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            // 创建ConfigService,此处通过Properties方式进行创建,另一种演示serviceaddr获取configService.
            // 原理上都是通过 ConfigFactory.createConfigService()去进行创建
            ConfigService configService = NacosFactory.createConfigService(properties);
            // ConfigService configService = NacosFactory.createConfigService(serverAddr);

            //***************************重点是这一句话,拿到了值*************************。
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println("配置内容是 : " + content);
           String getvalue= content.substring(content.indexOf("<fileName>")+10,content.indexOf("</fileName>"));
            System.out.println("截取出来的内容是 : " + getvalue);

            map.put("content", content);
            // 添加Listener,用以演示receive获取数据结果
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("recieve : " + configInfo);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });

//            // 推送config。将原有dataid中信息替换。
//            boolean isPublishOk = configService.publishConfig(dataId, group, "publish config content");
//            System.out.println("isPublishOk : " + isPublishOk);
//            map.put("isPublishOk", isPublishOk);
//
//            Thread.sleep(3000);
//            content = configService.getConfig(dataId, group, 5000);
//            System.out.println("Thread sleep 3000ms : " + content);
//            map.put("Thread sleep 3000ms : ", content);

//            // 删除指定dataid , group 配置
//            boolean isRemoveOk = configService.removeConfig(dataId, group);
//            System.out.println("remove " + dataId + "config is " + isRemoveOk);
//            Thread.sleep(3000);
//
//            content = configService.getConfig(dataId, group, 5000);
//            System.out.println("content after 5000ms "+content);
//            Thread.sleep(3000);
           return map;
        }

}

4、


//请求即可打印出来,即可拿到值。http://127.0.0.1:1027/springboot-nacos/config/get2
@Controller
@RequestMapping("config")
public class getvalue {

        @ResponseBody
        @RequestMapping("/get2")
        public Map getConfig() throws NacosException, InterruptedException {
            // 用以演示用,页面返回数据展示
            Map map = new HashMap();
            //  服务地址。本机演示故写localhost。请根据实际情况替换对应IP
            String serverAddr = "localhost";
            // 下面两个选项要和nacos里面新建的两个选项要一 一匹配
            String dataId = "nacos-spring";
            String group = "one-group";
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, serverAddr);
            // 创建ConfigService,此处通过Properties方式进行创建,另一种演示serviceaddr获取configService.
            // 原理上都是通过 ConfigFactory.createConfigService()去进行创建
            ConfigService configService = NacosFactory.createConfigService(properties);
            // ConfigService configService = NacosFactory.createConfigService(serverAddr);

            //***************************重点是这一句话,拿到了值*************************。
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println("配置内容是 : " + content);
           String getvalue= content.substring(content.indexOf("<fileName>")+10,content.indexOf("</fileName>"));
            System.out.println("截取出来的内容是 : " + getvalue);

            map.put("content", content);
            // 添加Listener,用以演示receive获取数据结果
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    System.out.println("recieve : " + configInfo);
                }
                @Override
                public Executor getExecutor() {
                    return null;
                }
            });

//            // 推送config。将原有dataid中信息替换。
//            boolean isPublishOk = configService.publishConfig(dataId, group, "publish config content");
//            System.out.println("isPublishOk : " + isPublishOk);
//            map.put("isPublishOk", isPublishOk);
//
//            Thread.sleep(3000);
//            content = configService.getConfig(dataId, group, 5000);
//            System.out.println("Thread sleep 3000ms : " + content);
//            map.put("Thread sleep 3000ms : ", content);

//            // 删除指定dataid , group 配置
//            boolean isRemoveOk = configService.removeConfig(dataId, group);
//            System.out.println("remove " + dataId + "config is " + isRemoveOk);
//            Thread.sleep(3000);
//
//            content = configService.getConfig(dataId, group, 5000);
//            System.out.println("content after 5000ms "+content);
//            Thread.sleep(3000);
           return map;
        }

}

章节2:

python代码实现

import nacos
import json
import time

##https://github.com/nacos-group/nacos-sdk-python

SERVER_ADDRESSES = "124.71.37.145:8848"
NAMESPACE ="bf40655e-b1ad-4ea3-9af8-8b57f62a0fed"

#client
client = nacos.NacosClient(SERVER_ADDRESSES,namespace=NAMESPACE,username="nacos",password="nacos")


#get config

data_id = "user.json"
group ="DEFAULT_GROUP"
print(type(client.get_config(data_id,group))) ##返回的是字符串
json_data = json.loads(client.get_config(data_id,group))
print(json_data)



def test_cb(args):
    print("配置文件发生变化")
    print(args)

if __name__ == '__main__':
    print(client.get_config(data_id, group))

    print(client.add_config_watcher(data_id,group,test_cb))
    time.sleep(3000)





章节3:go语言集成nacos

package main

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"time"
)

func main() {
	fmt.Println("begin")
	sc := []constant.ServerConfig{
		{
			IpAddr: "124.71.37.145",
			Port:   8848,
		},
	}
	or a more graceful way to create ServerConfig
	//_ = []constant.ServerConfig{
	//	*constant.NewServerConfig(
	//		"124.71.37.145",
	//		8848,
	//		constant.WithScheme("http"),
	//		constant.WithContextPath("/nacos")),
	//}

	cc := constant.ClientConfig{
		NamespaceId:         "bf40655e-b1ad-4ea3-9af8-8b57f62a0fed", //namespace id
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}

	fmt.Println(constant.WINDOWS_LEGAL_NAME_SPLITER)

	// a more graceful way to create config client
	client, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &cc,
			ServerConfigs: sc,
		},
	)

	if err != nil {
		panic(err)
	}

	//get config . 这里dataid和group 修改对应的
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: "user.json",
		Group:  "DEFAULT_GROUP",
	})
	fmt.Println("GetConfig,config :" + content)


	client.ListenConfig(vo.ConfigParam{
		DataId: "user.json",
		Group:  "DEFAULT_GROUP",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("配置文件发生变化")
			fmt.Println("group:"+group+",dataId:"+dataId+",data:"+data)
			
		},
	})

	time.Sleep(500*time.Second)


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值