Zookeeper实现分布式应用的(主节点HA)及客户端动态更新主节点状态

某分布式系统中,主节点可以有多台,可以动态上下线
任意一台客户端都能实时感知到主节点服务器的上下线
服务端逻辑:

服务端启动时在zookeeper集群中 /services节点写入一个临时节点,该临时节点内容为该节点的名称。当服务端下线或者宕机时zookeeper会将该节点删除 

客户端逻辑

客户端启动时会查找/services 下所有节点 并将节点名输出,当节点变化时,会重新查找所有节点,并将节点名输出 
 import org.apache.zookeeper.CreateMode import org.apache.zookeeper.Watcher import org.apache.zookeeper.ZooDefs import org.apache.zookeeper.ZooKeeper /** * 服务端 */ object DistributedServer {  private val CONNECT_STRING: String = "192.168.84.132:2181,192.168.84.133:2181,192.168.84.134:2181"  private val SESSION_TIMEOUT: Int = 2000  private val zooKeeper: ZooKeeper by lazy { ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, Watcher { event ->  println("${event?.type}-->${event?.path}")  zooKeeper.getChildren("/", true) }) } @JvmStatic fun main(args: Array<String>) { val serviceName = args[0] zooKeeper.create("/services/service", serviceName.toByteArray(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL) println("serviceName --> $serviceName create") println("$serviceName start working.....") Thread.sleep(Long.MAX_VALUE) } }
 import org.apache.zookeeper.Watcher import org.apache.zookeeper.ZooKeeper import org.apache.zookeeper.data.Stat /** * 客户端 */ object DistributedClient {  private val CONNECT_STRING: String = "192.168.84.132:2181,192.168.84.133:2181,192.168.84.134:2181"  private val SESSION_TIMEOUT: Int = 2000 private val zooKeeper: ZooKeeper by lazy { ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, Watcher { event -> println("${event?.type}-->${event?.path}") getServiceList() }) }  @Volatile private lateinit var services: ArrayList<String> @JvmStatic fun main(args: Array<String>) { getServiceList() println("client start working.....") Thread.sleep(Long.MAX_VALUE) } private fun getServiceList() {  val serviceList = zooKeeper.getChildren("/services", true)  val tempList = arrayListOf<String>() serviceList  .map { zooKeeper.getData("/services/" + it, false, Stat())} .mapTo(tempList) { String(it) } services = tempList println(services) } }

服务端

service

客户端

client

服务端上下线 客户端更新
这里写图片描述

原文链接:https://blog.csdn.net/a1837634447/article/details/78299408

原创文章,作者:优速盾-小U,如若转载,请注明出处:https://www.cdnb.net/bbs/archives/7757

(0)
上一篇 2022年8月20日
下一篇 2022年8月20日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

优速盾注册领取大礼包www.cdnb.net
/sitemap.xml