文章目录
前言
学习任何技术请先熟读官方文档,本篇仅仅是一个快速开始
,版本锁定在 2.1.0
官方网站:https://nacos.io/zh-cn/docs/what-is-nacos.html
一、下载和单机启动
章节地址: https://github.com/alibaba/nacos/releases
方式一:下载源码构建
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
ls -al distribution/target/
// change the $version to your actual path
cd distribution/target/nacos-server-$version/nacos/bin
网络原因卡顿的话,可以使用gitee地址
码云仓库地址: https://gitee.com/mirrors/Nacos
注意,windows使用powershell模式会构建失败,请用cmd
方式二:下载文本版本解压后启动
下载地址: https://github.com/alibaba/nacos/releases
2.1.0:https://github.com/alibaba/nacos/releases/download/2.1.0/nacos-server-2.1.0.zip
单机启动命令, windows 使用对应 .cmd
sh startup.sh -m standalone
windows下启动示例:
输入地址:http://192.168.181.1:8848/nacos/index.htm
帐号密码默认 nacos
集群部署:https://nacos.io/zh-cn/docs/cluster-mode-quick-start.html
二、Java的SDK:nacos-client
nacos 服务端默认不开启鉴权,权限认证章节参考官网:https://nacos.io/zh-cn/docs/auth.html
nacos 默认 namespace 是 public,nacos 自带的鉴权体系也是粒度到
namespace
的读写上
一般来说,如果小规模应用,可以使用 namespace 区分多套环境(dev test prew)
大规模应用,最好不同环境单独部署nacos集群,namespace用来区分租户(项目组or团队or应用等)
下文示例代码若无特殊说明,均为未开启鉴权、默认 public 的 namespace 的情况
1. 导包
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.1.0</version>
</dependency>
2. config 相关 API
更多配置参数参考 https://nacos.io/zh-cn/docs/system-configurations.html
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
// properties.put(PropertyKeyConst.NAMESPACE, "name1");
// properties.put(PropertyKeyConst.USERNAME, "ZT-group-app");
// properties.put(PropertyKeyConst.PASSWORD, "password");
ConfigService configService = NacosFactory.createConfigService(properties);
String dataId = "my-config";
// 发布配置,注意 第二个参数 group 传null或空串,就会默认为 DEFAULT_GROUP
configService.publishConfig(dataId, null, "config content xxxx", ConfigType.TEXT.getType());
// 获取配置, 此处可能立马获取返回的是null,后续章节分析
System.out.println("读取配置:" + configService.getConfig(dataId, null,5000));
// 监听器相关API
Listener listener = new Listener() {
@Override
public Executor getExecutor() {
// 返回null时使用内置的线程池执行,内置线程池最多5个,如果满了则占用拉取线程执行
System.out.println("==== 获取 executor=====");
return null;
}
@Override
@SneakyThrows
public void receiveConfigInfo(String configInfo) {
// 接受消息的处理方法
System.out.println("收到消息变更===》" + configInfo);
}
};
// 添加监听, 此时,可能会收到上一步发送出来的消息
configService.addListener(dataId, null, listener);
// 测试内容变更
configService.publishConfig(dataId, null, "change content xxxx");
Thread.sleep(5000);
// 此处每隔开1s变更一次配置,发现监听线程每到执行周期时只会拉取到最新的配置
for (int i = 0; i < 10; i++) {
System.out.println("== 发送消息 " + i + " ====&