Around Nacos: 环境搭建 & 项目结构

作为 Nacos 的开篇,我们首先先了解下 Nacos 的项目开发环境的搭建,和基础的项目结构和架构。

开发环境搭建

打开 nacos 的官网一键选择 git clone

1
git clone https://github.com/alibaba/nacos.git

模块

我们先看看项目的模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ tree . --dirsfirst -L 1
.
├── address
├── api
├── auth
├── client
├── cmdb
├── common
├── config
├── consistency
├── console
├── console-ui
├── core
├── distribution
├── doc
├── example
├── istio
├── naming
├── resources
├── style
├── sys
├── test
└── pom.xml
  • address: Nacos 地址服务器模块:这个模块有点难以理解,在社区的 Nacos环境隔离 有所涉及,也就是我们将不同的 Nacos Endpoint 切分为不同的 Group,类似于 DNS 的地域解析的方式,在发布清单中,此功能的作者也对此有所解释 地址服务器模块
  • api: Nacos 的 API 层,将大部分的 API 对象都抽象到此处
  • auth: Nacos 的鉴权实现
  • client: Nacos 的客户端 SDK
  • cmdb: Nacos CMDB 模块,对接外部的 CMDB,可以根据注册的信息获得一些额外的信息,在链接中的原文有所涉及。
  • config: Nacos 配置中心模块,后文重点分析
  • consistency: Nacos 一致性协议模块,将 AP CP 等实现方式都单独放置此处
  • console: Nacos 控制台
  • console-ui: Nacos 控制台的 UI
  • core: Nacos 的核心模块
  • distribution: 分发二进制所需要的一些额外的脚本
  • example: Nacos 使用示例
  • naming: Nacos 注册中心模块
  • sys: 和当前的运行环境相关的一些代码

Example

获取到源码,之后我们可以在 nacos-example 子模块中找到 启动的模板。

maingithub
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public static void main(String[] args) throws NacosException, InterruptedException {
Properties properties = new Properties();
properties.setProperty("serverAddr", System.getProperty("serverAddr"));
properties.setProperty("namespace", System.getProperty("namespace"));
NamingService naming = NamingFactory.createNamingService(properties);

naming.registerInstance("nacos.test.3", "11.11.11.11", 8888, "TEST1");
System.out.println("instances after register: " + naming.getAllInstances("nacos.test.3"));

Executor executor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),
new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("test-thread");
return thread;
}
});
}

可见 Nacos 所有的模块都是可以独立启动的,这里直接启动的 Naming(服务发现) 我们也可以单独启动 Config(配置中心)

如果需要本地开发,我们当然不希望使用上面那种 in code 的方式,当然希望跑起一个完整的 Nacos 因此我们需要

Run Standalone

对于 Nacos 来说,标准的线上环境使用 集群模式 进行运行,而我们在本地开发只需要使用 nacos.standalone 配置项进行本地化的运行即可。

找到 Nacos 项目运行即可,记得要加一下启动参数 -Dnacos.standalone=true

Nacosgithub
1
2
3
4
5
6
7
8
9
@SpringBootApplication(scanBasePackages = "com.alibaba.nacos")
@ServletComponentScan
@EnableScheduling
public class Nacos {

public static void main(String[] args) {
SpringApplication.run(Nacos.class, args);
}
}

然后打开 http://127.0.0.1:8848/nacos/index.html 就看到我们熟悉的页面了。