nats安装使用

NATS 是一个高性能的消息传递系统,常用于微服务架构中的通信。下面介绍如何配置和使用 NATS,包括服务器安装、客户端配置以及安全设置。

1. 安装 NATS 服务器

方式一:使用 Docker(推荐)

1
docker run -p 4222:4222 -p 8222:8222 --name nats-server nats:latest
  • 4222:客户端连接端口
  • 8222:监控端口(可选)

方式二:直接下载二进制文件

NATS 官网 下载对应系统的二进制文件,然后启动:

1
./nats-server

2. 基础配置文件

创建 nats.config 文件,配置基本参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# nats.config
port: 4222 # 客户端连接端口
http_port: 8222 # 监控端口

# 日志设置
log_file: "/var/log/nats.log"
debug: true
trace: true

# 集群配置(可选)
cluster {
listen: 0.0.0.0:6222
routes = [
nats-route://node1:6222,
nats-route://node2:6222
]
}

启动服务器时加载配置文件:

1
nats-server -c nats.config

3. 客户端配置

以 Node.js 为例,安装客户端库并连接 NATS:

1
npm install nats
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const { connect, StringCodec } = require('nats');

async function run() {
// 连接到 NATS 服务器
const nc = await connect({
servers: "localhost:4222", // 服务器地址
maxReconnectAttempts: 5, // 最大重连次数
reconnectTimeWait: 1000, // 重连间隔(毫秒)
});

// 发布消息
const sc = StringCodec();
nc.publish("subject", sc.encode("Hello NATS!"));

// 订阅消息
const sub = nc.subscribe("subject");
(async () => {
for await (const m of sub) {
console.log(`Received: ${sc.decode(m.data)}`);
}
console.log("Subscription closed");
})();

// 关闭连接
await nc.drain();
}

run();

4. 安全配置

(1) 基本认证

在配置文件中添加用户名和密码:

1
2
3
4
5
authorization {
user: nats-user
password: nats-pass
timeout: 2
}

客户端连接时提供凭证:

1
2
3
4
5
const nc = await connect({
servers: "localhost:4222",
user: "nats-user",
pass: "nats-pass",
});

(2) TLS 加密

生成证书后,在配置文件中启用 TLS:

1
2
3
4
5
6
tls {
cert_file: "/path/to/cert.pem"
key_file: "/path/to/key.pem"
ca_file: "/path/to/ca.pem"
verify: true
}

客户端连接时指定 TLS 选项:

1
2
3
const nc = await connect({
servers: "tls://localhost:4222",
});

5. 高级配置

(1) JetStream(持久化消息)

在配置文件中启用 JetStream:

1
2
3
4
5
jetstream: {
store_dir: "/var/nats/jetstream"
max_mem: 1GB
max_file: 10GB
}

(2) 集群配置

配置多个服务器形成集群:

1
2
3
4
5
6
7
8
9
10
11
# 节点1配置
cluster {
name: "my-cluster"
listen: 0.0.0.0:6222
routes = [
nats-route://node1:6222,
nats-route://node2:6222
]
}

# 节点2配置类似,修改 listen 地址

6. 常用命令

  • 启动服务器nats-server -c nats.config
  • 查看服务器状态nats server info
  • 发布消息nats pub subject "hello"
  • 订阅消息nats sub subject

7. 验证配置

使用 NATS CLI 工具验证配置是否正确:

1
2
3
4
5
# 安装 CLI
curl -sSL https://nats.io/download/nats-io/natscli/install.sh | sh

# 连接测试
nats --user nats-user --pass nats-pass pub test "Hello NATS"

通过以上配置,你可以搭建一个安全、高性能的 NATS 消息系统,支持微服务间的可靠通信。根据实际需求,可以进一步调整参数或添加高级功能(如流处理、负载均衡等)。