• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala Cluster类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中akka.cluster.Cluster的典型用法代码示例。如果您正苦于以下问题:Scala Cluster类的具体用法?Scala Cluster怎么用?Scala Cluster使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Cluster类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: FactorialFrontend

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

import scala.concurrent.duration._
import com.typesafe.config.ConfigFactory
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorSystem
import akka.actor.Props
import akka.cluster.Cluster
import akka.routing.FromConfig
import akka.actor.ReceiveTimeout

//#frontend
class FactorialFrontend(upToN: Int, repeat: Boolean) extends Actor with ActorLogging {

  val backend = context.actorOf(FromConfig.props(),
    name = "factorialBackendRouter")

  override def preStart(): Unit = {
    sendJobs()
    if (repeat) {
      context.setReceiveTimeout(10.seconds)
    }
  }

  def receive = {
    case (n: Int, factorial: BigInt) =>
      if (n == upToN) {
        log.debug("{}! = {}", n, factorial)
        if (repeat) sendJobs()
        else context.stop(self)
      }
    case ReceiveTimeout =>
      log.info("Timeout")
      sendJobs()
  }

  def sendJobs(): Unit = {
    log.info("Starting batch of factorials up to [{}]", upToN)
    1 to upToN foreach { backend ! _ }
  }
}
//#frontend

object FactorialFrontend {
  def main(args: Array[String]): Unit = {
    val upToN = 200

    val config = ConfigFactory.parseString("akka.cluster.roles = [frontend]").
      withFallback(ConfigFactory.load("factorial"))

    val system = ActorSystem("ClusterSystem", config)
    system.log.info("Factorials will start when 2 backend members in the cluster.")
    //#registerOnUp
    Cluster(system) registerOnMemberUp {
      system.actorOf(Props(classOf[FactorialFrontend], upToN, true),
        name = "factorialFrontend")
    }
    //#registerOnUp
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:62,代码来源:FactorialFrontend.scala


示例2: MetricsListener

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

import akka.actor.ActorLogging
import akka.actor.Actor

//#metrics-listener
import akka.cluster.Cluster
import akka.cluster.ClusterEvent.ClusterMetricsChanged
import akka.cluster.ClusterEvent.CurrentClusterState
import akka.cluster.NodeMetrics
import akka.cluster.StandardMetrics.HeapMemory
import akka.cluster.StandardMetrics.Cpu

class MetricsListener extends Actor with ActorLogging {
  val selfAddress = Cluster(context.system).selfAddress

  // subscribe to ClusterMetricsChanged
  // re-subscribe when restart
  override def preStart(): Unit =
    Cluster(context.system).subscribe(self, classOf[ClusterMetricsChanged])
  override def postStop(): Unit =
    Cluster(context.system).unsubscribe(self)

  def receive = {
    case ClusterMetricsChanged(clusterMetrics) =>
      clusterMetrics.filter(_.address == selfAddress) foreach { nodeMetrics =>
        logHeap(nodeMetrics)
        logCpu(nodeMetrics)
      }
    case state: CurrentClusterState => // ignore
  }

  def logHeap(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case HeapMemory(address, timestamp, used, committed, max) =>
      log.info("Used heap: {} MB", used.doubleValue / 1024 / 1024)
    case _ => // no heap info
  }

  def logCpu(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, processors) =>
      log.info("Load: {} ({} processors)", systemLoadAverage, processors)
    case _ => // no cpu info
  }
}

//#metrics-listener 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:47,代码来源:MetricsListener.scala


示例3: SimpleClusterListener

//设置package包名称以及导入依赖的类
package sample.cluster.simple

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    //#subscribe
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents,
      classOf[MemberEvent], classOf[UnreachableMember])
    //#subscribe
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:32,代码来源:SimpleClusterListener.scala


示例4: SimpleClusterListener2

//设置package包名称以及导入依赖的类
package sample.cluster.simple

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener2 extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    //#subscribe
    cluster.subscribe(self, classOf[MemberEvent], classOf[UnreachableMember])
    //#subscribe
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case state: CurrentClusterState =>
      log.info("Current members: {}", state.members.mkString(", "))
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:love1314sea,项目名称:akka-2.3.16,代码行数:33,代码来源:SimpleClusterListener2.scala


示例5: Registration

//设置package包名称以及导入依赖的类
package com.bob.scalatour.akka.cluster

import akka.actor.{ActorPath, ActorRef, Actor}
import akka.cluster.{Member, Cluster}
import akka.cluster.ClusterEvent.{MemberEvent, UnreachableMember, MemberUp, InitialStateAsEvents}

object Registration extends Serializable

trait EventMessage extends Serializable

case class RawNginxRecord(sourceHost: String, line: String) extends EventMessage

case class NginxRecord(sourceHost: String, eventCode: String, line: String) extends EventMessage

case class FilteredRecord(sourceHost: String, eventCode: String, line: String, logDate: String, realIp: String) extends EventMessage

abstract class ClusterRoledWorker extends Actor {

  // ????Cluster??
  val cluster = Cluster(context.system)
  // ????????????
  var workers = IndexedSeq.empty[ActorRef]

  @throws[Exception](classOf[Exception])
  override def preStart(): Unit = {
    super.preStart()
    // ??????
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents, classOf[MemberUp], classOf[UnreachableMember], classOf[MemberEvent])
  }

  @throws[Exception](classOf[Exception])
  override def postStop(): Unit = {
    cluster.unsubscribe(self)
    super.postStop()
  }

  def register(member: Member, createPath: (Member) => ActorPath): Unit = {
    val actorPath = createPath(member)
    println("Actor path: " + actorPath)
    val actorSelection = context.actorSelection(actorPath)
    actorSelection ! Registration
  }

}

 
开发者ID:bobxwang,项目名称:scalatour,代码行数:45,代码来源:ClusterWorker.scala


示例6: BeefTest

//设置package包名称以及导入依赖的类
package com.example

import java.time.Duration
import java.time.Instant
import java.util.concurrent.Executors

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.naoh.beef.Auth
import com.naoh.beef.Beef
import com.naoh.beef.Client
import com.naoh.beef.Region
import com.naoh.beef.Server
import com.naoh.beef.proto.echo.EchoGrpc
import com.naoh.beef.proto.echo.EchoReq
import com.typesafe.config.ConfigFactory

import scala.concurrent.Await
import scala.concurrent.ExecutionContext
import scala.util.Try


class BeefTest {

  val serverSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("server.conf").resolve())
  val clientSystem = ActorSystem("MyActorSystem", ConfigFactory.parseResources("client.conf").resolve())
  Cluster(serverSystem).join(Cluster(serverSystem).selfAddress)
  Cluster(clientSystem).join(Cluster(serverSystem).selfAddress)
  val serverCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))
  val clientCtx = ExecutionContext.fromExecutorService(Executors.newScheduledThreadPool(8))

  val region = Region("rg")
  val auth = Auth("au")

  Thread.sleep(1000)

  Beef(serverSystem)(
    Server(region)
      << EchoGrpc.bindService(EchoImpl, serverCtx))
  Thread.sleep(1000)

  val builder = Client(region, auth, clientCtx) connect Beef(clientSystem)
  val client = builder.build(new EchoGrpc.EchoBlockingStub(_, _))
  Thread.sleep(1000)

  val base = Instant.now
  Iterator.range(0, 3000).toSeq.toParArray.foreach{_ => Try(client.retEcho(EchoReq("12"))); print(".")}
  val record = Duration.between(base, Instant.now())

  println(s"\n\nDuration $record \n")

  Thread.sleep(2000)
  clientCtx.shutdown()
  serverCtx.shutdown()
  clientSystem.shutdown()
  serverSystem.shutdown()
} 
开发者ID:naoh87,项目名称:grpc-scala-experiment,代码行数:58,代码来源:BeefTest.scala


示例7: MetricsListener

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

import akka.actor.ActorLogging
import akka.actor.Actor
import akka.cluster.Cluster
import akka.cluster.metrics.ClusterMetricsEvent
import akka.cluster.metrics.ClusterMetricsChanged
import akka.cluster.ClusterEvent.CurrentClusterState
import akka.cluster.metrics.NodeMetrics
import akka.cluster.metrics.StandardMetrics.HeapMemory
import akka.cluster.metrics.StandardMetrics.Cpu
import akka.cluster.metrics.ClusterMetricsExtension

class MetricsListener extends Actor with ActorLogging {
  val selfAddress = Cluster(context.system).selfAddress
  val extension = ClusterMetricsExtension(context.system)

  // Subscribe unto ClusterMetricsEvent events.
  override def preStart(): Unit = extension.subscribe(self)
  
  // Unsubscribe from ClusterMetricsEvent events.
  override def postStop(): Unit = extension.unsubscribe(self)

  def receive = {
    case ClusterMetricsChanged(clusterMetrics) =>
      clusterMetrics.filter(_.address == selfAddress) foreach { nodeMetrics =>
        logHeap(nodeMetrics)
        logCpu(nodeMetrics)
      }
    case state: CurrentClusterState => // Ignore.
  }

  def logHeap(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case HeapMemory(address, timestamp, used, committed, max) =>
      log.info("Used heap: {} MB", used.doubleValue / 1024 / 1024)
    case _ => // No heap info.
  }

  def logCpu(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, cpuStolen, processors) =>
      log.info("Load: {} ({} processors)", systemLoadAverage, processors)
    case _ => // No cpu info.
  }
} 
开发者ID:seglo,项目名称:akka-cluster-conductr,代码行数:45,代码来源:MetricsListener.scala


示例8: SimpleClusterListener

//设置package包名称以及导入依赖的类
package sample.cluster.simple

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart
  override def preStart(): Unit = {
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents,
      classOf[MemberEvent], classOf[UnreachableMember])
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case SimpleConductRClusterApp.Ready =>
      sender() ! akka.Done
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:seglo,项目名称:akka-cluster-conductr,代码行数:32,代码来源:SimpleClusterListener.scala


示例9: SimpleClusterListener2

//设置package包名称以及导入依赖的类
package sample.cluster.simple

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener2 extends Actor with ActorLogging {

  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    cluster.subscribe(self, classOf[MemberEvent], classOf[UnreachableMember])
  }
  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive = {
    case state: CurrentClusterState =>
      log.info("Current members: {}", state.members.mkString(", "))
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case _: MemberEvent => // ignore
  }
} 
开发者ID:seglo,项目名称:akka-cluster-conductr,代码行数:31,代码来源:SimpleClusterListener2.scala


示例10: ClusterSystem

//设置package包名称以及导入依赖的类
package akka_in_action.cluster

import akka.actor.{ActorSystem, Props}
import akka.cluster.Cluster
import com.typesafe.config.{Config, ConfigFactory}

object ClusterSystem extends App {
  def loadCommonConfig: Config = ConfigFactory.load("cluster")

  def remoteConfig(hostname: String, port: Int, commonConfig: Config, isMaster: Boolean = false): Config = {
    //    ConfigFactory.invalidateCaches()
    val roles = if (isMaster)
      """["seed", "master"]""".stripMargin
    else
      """["seed"]""".stripMargin
    val remoteConfigString =
      s"""
         akka.remote.netty.tcp.hostname = $hostname
         akka.remote.netty.tcp.port = $port
         akka.cluster.roles = $roles
       """.stripMargin
    println(remoteConfigString)
    ConfigFactory.parseString(remoteConfigString).withFallback(commonConfig)
  }

  def startSeedNode(hostname: String, port: Int, commonConfig: Config, isMaster: Boolean = false): ActorSystem = {
    val seedConfig = remoteConfig(hostname, port, commonConfig, isMaster)
    ActorSystem("words", seedConfig)
  }

  def leaveCluster(system: ActorSystem): Unit = {
    val cluster = Cluster(system)
    cluster.leave(cluster.selfAddress)
  }

  val commonConfig = loadCommonConfig

  val system2551 = startSeedNode("127.0.0.1", 2551, commonConfig, true)
  val listener = system2551.actorOf(Props[ClusterDomainEventListener], "listener")

  Thread.sleep(1000)

  val system2552 = startSeedNode("127.0.0.1", 2552, commonConfig)
  val system2553 = startSeedNode("127.0.0.1", 2553, commonConfig)

  Thread.sleep(10000)

  1 to 6 foreach { _ => println("[DONE] ------------------->>> ") }

  leaveCluster(system2551)
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:52,代码来源:ClusterSystem.scala


示例11: ClusterDomainEventListener

//设置package包名称以及导入依赖的类
package akka_in_action.cluster

import akka.actor.{Actor, ActorLogging}
import akka.cluster.{Cluster, MemberStatus}
import akka.cluster.ClusterEvent._

class ClusterDomainEventListener extends Actor
  with ActorLogging {

  Cluster(context.system).subscribe(self, classOf[ClusterDomainEvent])

  def receive = {
    case MemberUp(member) => log.info(s"$member UP.")
    case MemberExited(member) => log.info(s"$member EXITED")
    case MemberRemoved(member, previousStatus) => {
      if(previousStatus == MemberStatus.exiting) {
        log.info(s"Member $member gracefully exited, REMOVED")
      } else {
        log.info(s"$member downed after unreachable, REMOVED")
      }
    }
    case UnreachableMember(member) => log.info(s"$member UNREACHABLE")
    case state: CurrentClusterState => log.info(s"Cluster state: $state")
  }

  override def postStop(): Unit = {
    Cluster(context.system).unsubscribe(self)
    super.postStop()
  }
} 
开发者ID:rockdragon,项目名称:fourthgala,代码行数:31,代码来源:ClusterDomainEventListener.scala


示例12: MetricsListener

//设置package包名称以及导入依赖的类
package sample.cluster.factorial

//#metrics-listener
import akka.actor.ActorLogging
import akka.actor.Actor
import akka.cluster.Cluster
import akka.cluster.metrics.ClusterMetricsEvent
import akka.cluster.metrics.ClusterMetricsChanged
import akka.cluster.ClusterEvent.CurrentClusterState
import akka.cluster.metrics.NodeMetrics
import akka.cluster.metrics.StandardMetrics.HeapMemory
import akka.cluster.metrics.StandardMetrics.Cpu
import akka.cluster.metrics.ClusterMetricsExtension

class MetricsListener extends Actor with ActorLogging {
  val selfAddress = Cluster(context.system).selfAddress
  val extension = ClusterMetricsExtension(context.system)

  // Subscribe unto ClusterMetricsEvent events.
  override def preStart(): Unit = extension.subscribe(self)
  
  // Unsubscribe from ClusterMetricsEvent events.
  override def postStop(): Unit = extension.unsubscribe(self)

  def receive = {
    case ClusterMetricsChanged(clusterMetrics) =>
      clusterMetrics.filter(_.address == selfAddress) foreach { nodeMetrics =>
        logHeap(nodeMetrics)
        logCpu(nodeMetrics)
      }
    case state: CurrentClusterState => // Ignore.
  }

  def logHeap(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case HeapMemory(address, timestamp, used, committed, max) =>
      log.info("Used heap: {} MB", used.doubleValue / 1024 / 1024)
    case _ => // No heap info.
  }

  def logCpu(nodeMetrics: NodeMetrics): Unit = nodeMetrics match {
    case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, cpuStolen, processors) =>
      log.info("Load: {} ({} processors)", systemLoadAverage, processors)
    case _ => // No cpu info.
  }
}
//#metrics-listener 
开发者ID:somethingconcon,项目名称:grocer,代码行数:47,代码来源:MetricsListener.scala


示例13: Launcher

//设置package包名称以及导入依赖的类
package com.edu.chat

import java.io.File

import akka.actor.ActorSystem
import akka.cluster.Cluster
import com.typesafe.config.{Config, ConfigFactory}

object Launcher {
  def main(args: Array[String]): Unit = {
    val config = ConfigFactory.parseFileAnySyntax(new File(args(0))).resolve()
    createActorSystem(config)
  }

  def createActorSystem(config: Config): ActorSystem = {
    implicit val actorSystem = ActorSystem.create("chat", config)
    val cluster = Cluster(actorSystem)
    cluster.registerOnMemberUp {
      actorSystem.actorOf(SupervisorActor.props(cluster), "SupervisorActor")
    }
    actorSystem
  }
} 
开发者ID:themirrortruth,项目名称:chat-akka,代码行数:24,代码来源:Launcher.scala


示例14: ClusteredActor

//设置package包名称以及导入依赖的类
package com.github.wildprairie.common.actors

import akka.actor.{Actor, ActorLogging}
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._


abstract class ClusteredActor extends Actor with ActorLogging {
  protected val cluster = Cluster(context.system)

  override def preStart(): Unit =
    cluster.subscribe(
      self,
      initialStateAsEvents,
      classOf[MemberEvent],
      classOf[UnreachableMember]
    )

  override def postStop(): Unit =
    cluster.unsubscribe(self)
} 
开发者ID:OpenWakfu,项目名称:wildprairie,代码行数:22,代码来源:ClusteredActor.scala


示例15: cluster

//设置package包名称以及导入依赖的类
package hk.edu.polyu.datamining.pamap2.actor

import akka.cluster.{Cluster, MemberStatus}
import hk.edu.polyu.datamining.pamap2.actor.MessageProtocol.ResponseClusterComputeInfo
import hk.edu.polyu.datamining.pamap2.actor.UIActor.DispatchMessage
import hk.edu.polyu.datamining.pamap2.ui.{MonitorApplication, MonitorController}
import hk.edu.polyu.datamining.pamap2.utils.Lang
import hk.edu.polyu.datamining.pamap2.utils.Lang._


          cluster.leave(cluster.selfAddress)
          System.exit(0)
        }
        catch {
          case e: IllegalStateException => log warning "restarting UIActor with existing JavaFX Application"
            MonitorController.restarted("UIActor is restarted")
        }
      })
    }
  }

  def cluster = Cluster(context.system)

  override def receive: Receive = {
    case DispatchMessage(msg) => SingletonActor.Dispatcher.proxy ! msg
    //    case RequestClusterComputeInfo => SingletonActor.Dispatcher.proxy ! RequestClusterComputeInfo
    //      log info "asking cluster info"
    case ResponseClusterComputeInfo(clusterComputeInfo) => MonitorController.receivedNodeInfos(clusterComputeInfo)
    //      log info "received cluster compute info"
    case msg =>
      showError(s"unsupported message : $msg")
  }
} 
开发者ID:polyu-datamining-2016,项目名称:data-mining-pamap2,代码行数:34,代码来源:UIActor.scala


示例16: Main

//设置package包名称以及导入依赖的类
package hk.edu.polyu.datamining.pamap2

import akka.actor._
import akka.cluster.Cluster
import com.rethinkdb.RethinkDB
import hk.edu.polyu.datamining.pamap2.actor.SingletonActor
import hk.edu.polyu.datamining.pamap2.database.DatabaseHelper
import hk.edu.polyu.datamining.pamap2.ui.MonitorController
import hk.edu.polyu.datamining.pamap2.utils.Lang.runnable

import scala.collection.JavaConverters._

object Main extends App {

  val nodeConfig = NodeConfig parse args

  // If a config could be parsed - start the system
  nodeConfig foreach { c =>
    val system = ActorSystem(c.clusterName, c.config)
    val cluster: Cluster = Cluster(system)

    
    SingletonActor.Dispatcher.init(system)

    if (cluster.selfRoles.contains("seed")) {
      // register self to seed node list (akka)
      cluster.join(cluster.selfAddress)
    }
    else if (cluster.selfRoles.contains("ui"))
    // register a UIActor
      system.actorOf(Props[actor.UIActor])
    else
    // register a ComputeActor
      system.actorOf(Props[actor.ComputeActor])
  }

  def config = nodeConfig.get.config
} 
开发者ID:polyu-datamining-2016,项目名称:data-mining-pamap2,代码行数:39,代码来源:Main.scala


示例17: DiceActor

//设置package包名称以及导入依赖的类
package actors

import akka.actor._
import play.api.libs.concurrent.Execution.Implicits.defaultContext

import akka.cluster.Cluster
import akka.cluster.ddata.DistributedData
import akka.cluster.ddata.Replicator
import akka.cluster.ddata.Replicator._
import akka.cluster.ddata.GSet
import akka.cluster.ddata.GSetKey
import akka.cluster.ddata.LWWRegister
import akka.cluster.ddata.LWWRegisterKey

import play.api.Logger
import akka.event.LoggingReceive

import dicebot._ // import DiceBot

class DiceActor extends Actor {
  val dice = new DiceBot()
  val replicator = DistributedData(context.system).replicator
  implicit val node = Cluster(context.system)

  def topicMsgKey(topic: String) = LWWRegisterKey[ChatMessage](topic + "-lwwreg")

  def receive = LoggingReceive {
    case ChatMessage(topic, uid, msg, date) =>
      val commandResult = dice.commandCheck(msg)
      if (commandResult != None) {
        val diceMessage = ChatMessage(topic, "DiceBot: ", msg + "\n-> " + commandResult.get, date)
        replicator ! Update(GSetKey[ChatMessage](topic), GSet.empty[ChatMessage], WriteLocal) {
          _ + diceMessage
        }
        replicator ! Update(topicMsgKey(topic), LWWRegister[ChatMessage](null), WriteLocal) {
          reg => reg.withValue(diceMessage)
        }
        replicator ! FlushChanges
      }
      Logger.debug("DiceActor get: " + msg)
  }
} 
开发者ID:hyphon81,项目名称:en-taku,代码行数:43,代码来源:DiceActor.scala


示例18: preStart

//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.wasp.core.cluster

import akka.actor.{Actor, ActorLogging}
import akka.cluster.{Metric, NodeMetrics, Cluster}
import akka.cluster.ClusterEvent._
import akka.cluster.Member
import akka.cluster.MemberStatus


  override def preStart(): Unit = cluster.subscribe(self, classOf[ClusterDomainEvent])

  override def postStop(): Unit = cluster.unsubscribe(self)

  def receive: Actor.Receive = {
    case MemberUp(member) =>
      onMemberUp(member)
    case UnreachableMember(member) =>
      onUnreachableMember(member)
    case MemberRemoved(member, previousStatus) =>
      onMemberRemoved(member, previousStatus)
    case ClusterMetricsChanged(forNode) =>
      forNode collectFirst {
        case m if m.address == cluster.selfAddress =>
          log.debug("{}", filter(m.metrics))
      }
    case _: MemberEvent =>
  }

  def filter(nodeMetrics: Set[Metric]): String = {
    val filtered = nodeMetrics collect { case v if v.name != "processors" => s"${v.name}:${v.value}" }
    s"NodeMetrics[${filtered.mkString(",")}]"
  }

  def onMemberUp(member: Member) = log.info("Member {} joined cluster.", member.address)

  def onUnreachableMember(member: Member) = log.info("Member detected as unreachable: {}", member)

  def onMemberRemoved(member: Member, previousStatus: MemberStatus) = log.info("Member is Removed: {} after {}", member.address, previousStatus)

} 
开发者ID:agile-lab-dev,项目名称:wasp,代码行数:41,代码来源:ClusterAware.scala


示例19: ClusterConfirmationActor

//设置package包名称以及导入依赖的类
package csw.services.location.commons

import akka.Done
import akka.actor.{Actor, Props}
import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import csw.services.location.commons.ClusterConfirmationActor.{HasJoinedCluster, IsMemberUp}

class ClusterConfirmationActor extends Actor {

  val cluster = Cluster(context.system)

  override def preStart(): Unit = cluster.subscribe(self, InitialStateAsEvents, classOf[MemberEvent])
  override def postStop(): Unit = cluster.unsubscribe(self)

  var done: Option[Done] = None
  var up: Option[Done]   = None

  override def receive: Receive = {
    case MemberUp(member) if member.address == cluster.selfAddress       ? done = Some(Done); up = Some(Done)
    case MemberWeaklyUp(member) if member.address == cluster.selfAddress ? done = Some(Done)
    case HasJoinedCluster                                                ? sender() ! done
    case IsMemberUp                                                      ? sender() ! up
  }

}

object ClusterConfirmationActor {
  def props() = Props(new ClusterConfirmationActor)

  case object HasJoinedCluster
  case object IsMemberUp
} 
开发者ID:tmtsoftware,项目名称:csw-prod,代码行数:34,代码来源:ClusterConfirmationActor.scala


示例20: Backend

//设置package包名称以及导入依赖的类
package cluster

import akka.actor.{Props, ActorSystem, RootActorPath, Actor}
import akka.actor.Actor.Receive
import akka.cluster.Cluster
import akka.cluster.ClusterEvent.MemberUp
import com.typesafe.config.ConfigFactory


class Backend extends Actor {
  val cluster = Cluster(context.system)

  override def preStart(): Unit = {
    cluster.subscribe(self, classOf[MemberUp])

  }

  override def postStop() = {
    cluster.unsubscribe(self)
  }

  override def receive: Receive = {
    case Add(num1, num2) =>
      println(s"============== I'm a backend with path ${self} and I received add operation ===============")
    case MemberUp(member) =>
      if (member.hasRole("frontend")) {
        context.actorSelection(RootActorPath(member.address) / "user" / "frontend") ! BackendRegistration
      }
  }
}

object Backend {
  def initiate(port: Int) = {
    val config = ConfigFactory.parseString(s"akka.remote.netty.tcp.port=$port").
      withFallback(ConfigFactory.load.getConfig("Backend"))

    val system = ActorSystem("ClusterSystem", config)

    val Backend = system.actorOf(Props[Backend], name = "Backend")

  }
}

case class Add(num1: Int, num2: Int)
case object BackendRegistration 
开发者ID:astray1988,项目名称:AkkaExplore,代码行数:46,代码来源:Backend.scala



注:本文中的akka.cluster.Cluster类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala DecisionTree类代码示例发布时间:2022-05-23
下一篇:
Scala KafkaConfig类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap