Nats 集群初探

nats支持在集群模式下运行节点,节点做成集群之后,可以达到支持高容量、弹性化和高可用的效果。官网的说法是:

NATS servers achieve this by gossiping about and connecting to, all of the servers they know, thus dynamically forming a full mesh. Once clients connect or re-connect to a particular server, they are informed about current cluster members. Because of this behavior, a cluster can grow, shrink and self heal. The full mesh does not necessarily have to be explicitly configured either.

Note that NATS clustered servers have a forwarding limit of one hop. This means that each nats-server instance will only forward messages that it has received from a client to the immediately adjacent nats-server instances to which it has routes. Messages received from a route will only be distributed to local clients.

For the cluster to successfully form a full mesh and NATS to function as intended and described throughout the documentation - temporary errors permitting - it is necessary that servers can connect to each other and that clients can connect to each server in the cluster.

至于模仿消息发送、消费,官网都有现成案例

# 安装 官网测试工具,不带认证
# 生产者工具
go get github.com/nats-io/go-nats-examples/tools/nats-pub
# 消费者工具
go get github.com/nats-io/go-nats-examples/tools/nats-sub
 
# 启动server
nats-server
 
# 先启动消费进程
nats-sub ">"
# 启动发送消息进程
nats-pub hello world
 
# 访问远程机器
nats-sub -s nats://server:port ">"
# 官网示例地址
nats-sub -s nats://demo.nats.io ">"

 集群模式
刚开始没弄明白集群模式怎么回事儿,只看了官方例子

Running a Simple Cluster
Here is a simple cluster running on the same machine:

# Server A - the 'seed server'
nats-server -p 4222 -cluster nats://localhost:4248
# Server B
nats-server -p 5222 -cluster nats://localhost:5248 -routes nats://localhost:4248
# Check the output of the server for the selected client and route ports.
# Server C
 nats-server -p 6222 -cluster nats://localhost:6248 -routes nats://localhost:4248
# Check the output of the server for the selected client and route ports.

观察数字规律,猜测4222/5222/6222 是一组,*248是一组。按照这个猜想,首先我尝试作为消费者监听4258

nats-sub -s nats://127.0.0.1:5222 ">"

发现报错了

作为消费者监听在5222上,无报错,然后作为生产者监听在4248上,并且发送消息

nats-pub -s nats://127.0.0.1:4248 hello world

至此差不多流程搞清楚了
nats 集群,只要消费者监听*222端口中的任一个,比如我刚才模拟的是连接到5222,那么就可以跟其他任一*248的生产者通信。

现在我们模拟有一个节点宕机的情况,比如把当前消费者监听的5222对应的进程停掉,会发生什么情况?

可以看到消费者自动转监听4222端口了。
为了准确性,可以多尝试几次,看看是不是每次都转而去监听5222端口,或者把5222端口起来,看发生情况。()这里就不尝试了。)
但生产者如果想连接跟5222端口配套的5248端口,就不可以了,因为5248端口进程已经被杀死,只能转而去监听其他端口发生消息。也就是说,如果生产者放想发送消息,需要维护一个列表,这个列表是所有集群节点的route server端口,否则生产者将无法发送消息。

总结:消费者如果监听端口不断开,可以连接任意集群节点,当监听的集群节点端口时,会转而监听其他端口。

几个大胆的猜想

  • 集群之间的节点、端口必须可以相互通信
  • 消费者也必须可以跟任意节点的端口通信。
  • 生产者需要维护一个可用节点列表

以上是个人的测试环境学习总结,欢迎高手拍砖

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值