kka-typed(5) - cluster:集群節點狀態監視

来源:https://www.cnblogs.com/tiger-xc/archive/2020/06/07/13062642.html
-Advertisement-
Play Games

akka-cluster對每個節點的每種狀態變化都會在系統消息隊列里發佈相關的事件。通過訂閱有關節點狀態變化的消息就可以獲取每個節點的狀態。這部分已經在之前關於akka-cluster的討論里介紹過了。由於akka-typed里採用了新的消息交流協議,而系統消息的發佈和訂閱也算是消息交換,也受交流協 ...


 akka-cluster對每個節點的每種狀態變化都會在系統消息隊列里發佈相關的事件。通過訂閱有關節點狀態變化的消息就可以獲取每個節點的狀態。這部分已經在之前關於akka-cluster的討論里介紹過了。由於akka-typed里採用了新的消息交流協議,而系統消息的發佈和訂閱也算是消息交換,也受交流協議約束。所以想通過重寫以前示範的ClusterMemberStatus來瞭解一下akka-typed環境下節點狀態變化消息監聽的一些機制。

我們需要一個actor來訂閱系統發佈的節點狀態變化消息。這裡涉及到系統、actor兩端的信息交流。假設向系統訂閱是一種消息的發送,那麼得到的節點狀態變化消息就是系統的response了。先看看actor里的消息定義:

 

object MonitorActor {
  sealed trait ClusterEvent
  private case class MemberStatus(event: MemberEvent) extends ClusterEvent
  private case class ReachStatus(event: ReachabilityEvent) extends ClusterEvent

  def apply(): Behavior[ClusterEvent] = Behaviors.setup[ClusterEvent] { ctx =>
    val memberEventAdapter: ActorRef[MemberEvent] = ctx.messageAdapter(MemberStatus)
    val reachEventAdapter: ActorRef[ReachabilityEvent] = ctx.messageAdapter(ReachStatus)
    Cluster(ctx.system).subscriptions ! Subscribe(memberEventAdapter,classOf[MemberEvent])
    Cluster(ctx.system).subscriptions ! Subscribe(reachEventAdapter,classOf[ReachabilityEvent])

...
}

首先,response 分為 MemberEvent, ReachabilityEvent兩種。MonitorActor處理的消息類型是ClusterEvent。為了處理系統返回的response類型,即MemberEvent,ReachabilityEvent,必須提供這兩種類型到ClusterEvent的轉換。通過ctx.messageAdapter登記MemberEvent -> MemberStatus, ReachabilityEvent -> ReachStatus兩種類型轉換機制使MonitorActor可以接收到MemberStatus, ReachStatus兩種消息:

object MonitorActor {
  sealed trait ClusterEvent
  private case class MemberStatus(event: MemberEvent) extends ClusterEvent
  private case class ReachStatus(event: ReachabilityEvent) extends ClusterEvent

  def apply(): Behavior[ClusterEvent] = Behaviors.setup[ClusterEvent] { ctx =>
    val memberEventAdapter: ActorRef[MemberEvent] = ctx.messageAdapter(MemberStatus)
    val reachEventAdapter: ActorRef[ReachabilityEvent] = ctx.messageAdapter(ReachStatus)
    Cluster(ctx.system).subscriptions ! Subscribe(memberEventAdapter,classOf[MemberEvent])
    Cluster(ctx.system).subscriptions ! Subscribe(reachEventAdapter,classOf[ReachabilityEvent])
    Behaviors.receiveMessage { event =>
      event match {
        case MemberStatus(status) =>
          status match {
            case MemberJoined(member) =>
              ctx.log.info("**************** Member joined: [{}] ***************", member.address)
            case MemberJoined(member) =>
              ctx.log.info("**************** Member joined: [{}] ***************", member.address)
            case MemberUp(member) =>
              ctx.log.info("**************** Member is Up: [{}] ***************", member.address)
            case MemberRemoved(member, previousStatus) =>
              ctx.log.info("**************** Member is Removed: [{}] after {} ***************",
                member.address, previousStatus)
            case MemberLeft(member) =>
              ctx.log.info("**************** Member left: [{}] ***************", member.address)
            case MemberExited(member) =>
              ctx.log.info("**************** Member exited: [{}] ***************", member.address)
            case _: MemberEvent => // ignore
          }
        case ReachStatus(status) =>
            status match {
              case UnreachableMember(member) =>
                ctx.log.info("**************** Member detected as unreachable: [{}] ***************", member)
              case ReachableMember(member) =>
                ctx.log.info("**************** Member back to reachable: [{}] ***************", member)
            }
      }
      Behaviors.same
    }
  }
}

還需要一個actor, 什麼都不幹。存粹構建一個MonitorActor:

object RootActor {
  def apply(): Behavior[Nothing] = Behaviors.setup[Nothing] {ctx =>
     ctx.spawn(MonitorActor(),"listner")
     Behaviors.empty
  }
}

好了,看看main是怎麼實現的吧:

object ClusterMemberStatus {
  import com.typesafe.config.ConfigFactory
  def main(args: Array[String]): Unit = {
    val ports =
      if (args.isEmpty)
        Seq(25251, 25252, 0)
      else
        args.toSeq.map(_.toInt)
    ports.foreach { port =>
      startup(port)
    }

  }

  def startup(port: Int): Unit = {
    val config = ConfigFactory.parseString(s"""
      akka.remote.artery.canonical.port=$port
      """).withFallback(ConfigFactory.load("cluster.conf"))
    ActorSystem[Nothing](RootActor(),"ClusterSystem",config)
  }

}

下麵是測試結果顯示:

22:14:52.755 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25251] ***************
22:14:52.810 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:51081] - Received InitJoinAck message from [Actor[akka://[email protected]:25251/system/cluster/core/daemon#313431252]] to [akka://[email protected]:51081]
22:14:52.825 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Node [akka://[email protected]:51081] is JOINING, roles [dc-default]
22:14:52.825 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member joined: [akka://[email protected]:51081] ***************
22:14:52.829 [ClusterSystem-akka.actor.internal-dispatcher-7] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:25251] - Node added [UniqueAddress(akka://[email protected]:51081,567025403336682144)]
22:14:52.858 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:51081] - Welcome from [akka://[email protected]:25251]
22:14:52.858 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25251] ***************
22:14:52.858 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member joined: [akka://[email protected]:51081] ***************
22:14:52.858 [ClusterSystem-akka.actor.internal-dispatcher-13] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:51081] - Node added [UniqueAddress(akka://[email protected]:25251,6076326462170320177)]
22:14:53.044 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Leader is moving node [akka://[email protected]:51081] to [Up]
22:14:53.044 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:51081] ***************
22:14:53.679 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:51081] ***************
22:14:57.707 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Received InitJoin message from [Actor[akka://[email protected]:25252/system/cluster/core/daemon/joinSeedNodeProcess-1#1472023843]] to [akka://[email protected]:25251]
22:14:57.707 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Sending InitJoinAck message from node [akka://[email protected]:25251] to [Actor[akka://[email protected]:25252/system/cluster/core/daemon/joinSeedNodeProcess-1#1472023843]] (version [2.6.5])
22:14:57.732 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25252] - Received InitJoinAck message from [Actor[akka://[email protected]:25251/system/cluster/core/daemon#313431252]] to [akka://[email protected]:25252]
22:14:57.734 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Node [akka://[email protected]:25252] is JOINING, roles [dc-default]
22:14:57.735 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member joined: [akka://[email protected]:25252] ***************
22:14:57.735 [ClusterSystem-akka.actor.internal-dispatcher-26] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:25251] - Node added [UniqueAddress(akka://[email protected]:25252,-6913064885699273532)]
22:14:57.737 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25252] - Welcome from [akka://[email protected]:25251]
22:14:57.737 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25251] ***************
22:14:57.738 [ClusterSystem-akka.actor.internal-dispatcher-30] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:25252] - Node added [UniqueAddress(akka://[email protected]:25251,6076326462170320177)]
22:14:57.738 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member joined: [akka://[email protected]:25252] ***************
22:14:57.738 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:51081] ***************
22:14:57.738 [ClusterSystem-akka.actor.internal-dispatcher-30] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:25252] - Node added [UniqueAddress(akka://[email protected]:51081,567025403336682144)]
22:14:57.740 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member joined: [akka://[email protected]:25252] ***************
22:14:57.740 [ClusterSystem-akka.actor.internal-dispatcher-16] DEBUG akka.cluster.typed.internal.receptionist.ClusterReceptionist - ClusterReceptionist [akka://[email protected]:51081] - Node added [UniqueAddress(akka://[email protected]:25252,-6913064885699273532)]
22:14:58.134 [ClusterSystem-akka.actor.default-dispatcher-3] INFO akka.cluster.Cluster - Cluster Node [akka://[email protected]:25251] - Leader is moving node [akka://[email protected]:25252] to [Up]
22:14:58.134 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25252] ***************
22:14:58.755 [ClusterSystem-akka.actor.default-dispatcher-3] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25252] ***************
22:14:59.146 [ClusterSystem-akka.actor.default-dispatcher-14] INFO com.learn.akka.MonitorActor$ - **************** Member is Up: [akka://[email protected]:25252] ***************

下麵是本次示範的全部源代碼:

build.sbt

name := "learn-akka-typed"

version := "0.1"

scalaVersion := "2.13.1"
scalacOptions in Compile ++= Seq("-deprecation", "-feature", "-unchecked", "-Xlog-reflective-calls", "-Xlint")
javacOptions in Compile ++= Seq("-Xlint:unchecked", "-Xlint:deprecation")

val AkkaVersion = "2.6.5"
val AkkaPersistenceCassandraVersion = "1.0.0"


libraryDependencies ++= Seq(
  "com.typesafe.akka" %% "akka-cluster-sharding-typed" % AkkaVersion,
  "com.typesafe.akka" %% "akka-persistence-typed" % AkkaVersion,
  "com.typesafe.akka" %% "akka-persistence-query" % AkkaVersion,
  "com.typesafe.akka" %% "akka-serialization-jackson" % AkkaVersion,
  "com.typesafe.akka" %% "akka-persistence-cassandra" % AkkaPersistenceCassandraVersion,
  "com.typesafe.akka" %% "akka-slf4j" % AkkaVersion,
  "ch.qos.logback"     % "logback-classic"             % "1.2.3"
)

cluster.conf

akka {
  actor {
    provider = cluster

    serialization-bindings {
      "com.learn.akka.CborSerializable" = jackson-cbor
    }
  }
  remote {
    artery {
      canonical.hostname = "127.0.0.1"
      canonical.port = 0
    }
  }
  cluster {
    seed-nodes = [
      "akka://[email protected]:25251",
      "akka://[email protected]:25252"]
  }
}

ClusterMemberStatus.scala

package com.learn.akka
import akka.actor.typed._
import akka.actor.typed.scaladsl.Behaviors
import akka.cluster.ClusterEvent._
import akka.cluster.typed.Subscribe
import akka.cluster.typed.Cluster
import akka.actor.typed.ActorSystem

object MonitorActor {
  sealed trait ClusterEvent
  private case class MemberStatus(event: MemberEvent) extends ClusterEvent
  private case class ReachStatus(event: ReachabilityEvent) extends ClusterEvent

  def apply(): Behavior[ClusterEvent] = Behaviors.setup[ClusterEvent] { ctx =>
    val memberEventAdapter: ActorRef[MemberEvent] = ctx.messageAdapter(MemberStatus)
    val reachEventAdapter: ActorRef[ReachabilityEvent] = ctx.messageAdapter(ReachStatus)
    Cluster(ctx.system).subscriptions ! Subscribe(memberEventAdapter,classOf[MemberEvent])
    Cluster(ctx.system).subscriptions ! Subscribe(reachEventAdapter,classOf[ReachabilityEvent])
    Behaviors.receiveMessage { event =>
      event match {
        case MemberStatus(status) =>
          status match {
            case MemberJoined(member) =>
              ctx.log.info("**************** Member joined: [{}] ***************", member.address)
            case MemberJoined(member) =>
              ctx.log.info("**************** Member joined: [{}] ***************", member.address)
            case MemberUp(member) =>
              ctx.log.info("**************** Member is Up: [{}] ***************", member.address)
            case MemberRemoved(member, previousStatus) =>
              ctx.log.info("**************** Member is Removed: [{}] after {} ***************",
                member.address, previousStatus)
            case MemberLeft(member) =>
              ctx.log.info("**************** Member left: [{}] ***************", member.address)
            case MemberExited(member) =>
              ctx.log.info("**************** Member exited: [{}] ***************", member.address)
            case _: MemberEvent => // ignore
          }
        case ReachStatus(status) =>
            status match {
              case UnreachableMember(member) =>
                ctx.log.info("**************** Member detected as unreachable: [{}] ***************", member)
              case ReachableMember(member) =>
                ctx.log.info("**************** Member back to reachable: [{}] ***************", member)
            }
      }
      Behaviors.same
    }
  }
}
object RootActor {
  def apply(): Behavior[Nothing] = Behaviors.setup[Nothing] {ctx =>
     ctx.spawn(MonitorActor(),"listner")
     Behaviors.empty
  }
}
object ClusterMemberStatus {
  import com.typesafe.config.ConfigFactory
  def main(args: Array[String]): Unit = {
    val ports =
      if (args.isEmpty)
        Seq(25251, 25252, 0)
      else
        args.toSeq.map(_.toInt)
    ports.foreach { port =>
      startup(port)
    }

  }

  def startup(port: Int): Unit = {
    val config = ConfigFactory.parseString(s"""
      akka.remote.artery.canonical.port=$port
      """).withFallback(ConfigFactory.load("cluster.conf"))
    ActorSystem[Nothing](RootActor(),"ClusterSystem",config)
  }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 列表標簽 無序列表: 無序列表是一個項目的列表,此列項目使用粗體圓點(典型的小黑圓圈)進行標記。 無序列表使用 <ul> 標簽 <ul> <li>劉備</li> <li>關羽</li> <li>孫尚香</li> <li>諸葛亮</li> <li>劉禪</li> </ul> 有序列表: 有序列表也是一 ...
  • # 從零開始的前端生活-理解content(二) 應用 清除浮動 偽元素加content最常見的應用是清除浮動帶來的影響 .clear::after{ content:''; display:table; clear:both; } 字元內容的生成 content還可以插入Unicode字元(萬國 ...
  • 關於《SpringBoot-2.3容器化技術》系列 《SpringBoot-2.3容器化技術》系列,旨在和大家一起學習實踐2.3版本帶來的最新容器化技術,讓咱們的Java應用更加適應容器化環境,在雲計算時代依舊緊跟主流,保持競爭力; 全系列文章分為主題和輔助兩部分,主題部分如下: 《體驗Spring ...
  • 20.裝飾器 20.1 函數基礎知識 在Python中函數為一等公民,我們可以: 把函數賦值給變數 在函數中定義函數 在函數中返回函數 把函數傳遞給函數 20.1.1 把函數賦值給變數 在Python里,函數是對象,因此可以把它賦值給變數,如下所示: def hello(name="Surpass" ...
  • 關於《SpringBoot-2.3容器化技術》系列 《SpringBoot-2.3容器化技術》系列,旨在和大家一起學習實踐2.3版本帶來的最新容器化技術,讓咱們的Java應用更加適應容器化環境,在雲計算時代依舊緊跟主流,保持競爭力; 全系列文章分為主題和輔助兩部分,主題部分如下: 《體驗Spring ...
  • 刷到一個題腦子一下子沒有反應過來記錄一下子學習 如下: 答案就是A 這是為什麼呢 我乍一看nums1 new 了一個數組對象並把長度定為3,nums2聲明瞭一個數組,並定義了12345的值,如果 把nums2賦值給nums1它不是會越界嘛長度不一樣嘛,這是我乍一看的想法。 理解了好一會後發現這個題考 ...
  • 前端採用vue,後臺採用spring cloud微服務,進行前後端分離。公共模塊的搭建 ...
  • 題目:學習static定義靜態變數的用法。 程式分析:無。 實例: 1 #include<stdio.h> 2 int main() 3 { 4 void fun(); 5 for(int i=0;i<3;i++) 6 fun(); 7 return 0; 8 } 9 void fun() 10 { ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...