在Akka中,ActorSystem是一个重量级的结构,他需要分配多个线程,所以在实际应用中,ActorSystem通常是一个单例对象,我们可以使用这个ActorSystem创建很多Actor。
在Akka中,Actor负责通信,在Actor中有一些重要的生命周期方法。
preStart()方法:该方法在Actor对象构造方法执行后执行,整个Actor生命周期中仅执行一次。
receive()方法:该方法在Actor的preStart方法执行完成后执行,用于接收消息,会被反复执行。
import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration._
import scala.collection.mutable
/**
* Created by 57871 on 2018/11/1. */
class Master(val host: String,val port: Int ) extends Actor{
val idToWorker = new mutable.HashMap[String,WorkerInfo]
// WorkerInfo
val workers = new mutable.HashSet[WorkerInfo]() //使用set删除快, 也可用linkList //超时检查的间隔
val CHECK_INTERVAL = 15000
override def preStart(): Unit = {
println("preStart invoked")
import context.dispatcher
context.system.scheduler.schedule(0 millis,CHECK_INTERVAL millis,self,CheckTimeOutworker)
}
override def receive: Receive = {
case RegisterWorker(id,memory,coreNum) => {
//判断一下是不是注册过了
if (!idToWorker.contains(id)) {
println(s"开始注册 $id")
val worker = new WorkerInfo(id, memory, coreNum)
idToWorker(id) = worker
workers += worker
sender ! RegisteredWork(s"akka.tcp://MasterSystem@$host:$port/user/Master")
}
}
case Heartbeat(id) =>{
if(idToWorker.contains(id)){
println("接受心跳")
val workerInfo = idToWorker(id)
val currentTime = System.currentTimeMillis()
workerInfo.lastHeartBeat = currentTime
}
}
case CheckTimeOutworker =>{
val currentTime = System.currentTimeMillis()
val toRemove = workers.filter(x => currentTime -x.lastHeartBeat > CHECK_INTERVAL)
for(i <- toRemove){
workers -= i
idToWorker -= i.id
val id = i.id
println(s"去除掉失去心跳的worker $id ")
}
}
}
}
object Master{
def main(args: Array[String]): Unit = {
val host = args(0)
val port = args(1).toInt
//准备配置
val configure =
s"""
|akka.actor.provider = "akka.remote.RemoteActorRefProvider" |akka.remote.netty.tcp.hostname = "$host"
|akka.remote.netty.tcp.port = "$port"
""".stripMargin
val config = ConfigFactory.parseString(configure)
//ActorSystem 老大 辅助创建和监视下面的Actor
val actorSystem = ActorSystem("MasterSystem", config)
//创建Actor
val master = actorSystem.actorOf(Props(new Master(host,port)),"Master")
actorSystem.registerOnTermination()
}
}
import java.util.UUID
import akka.actor.{Actor, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration._
/**
* Created by 57871 on 2018/11/2. */
class Worker (val masterHost: String, val masterPort: Int, memory:Int, coreNum: Int) extends Actor{
var master: ActorSelection = _
val workerId = UUID.randomUUID().toString
val HEART_INTERVAL = 10000 override def preStart(): Unit = {
//跟Master建立连接
master = context.actorSelection(s"akka.tcp://MasterSystem@$masterHost:$masterPort/user/Master")
println("开始建立连接")
master ! RegisterWorker(workerId,memory,coreNum)
}
override def receive: Receive = {
case RegisteredWork(masterUrl) =>{
println(masterUrl)
//启动定时器发送心跳信息 import context.dispatcher
// 多长时间后执行 单位,多长时间执行一次 单位, 消息的接受者(直接给master发不好, 先给自己发送消息, 以后可以做下判断, 什么情况下再发送消息), 信息 context.system.scheduler.schedule(0 millis,HEART_INTERVAL millis,self,SendHeartbeat)
}
case SendHeartbeat =>{
println("send heartbeat")
master ! Heartbeat(workerId)
}
}
}
object Worker {
def main(args: Array[String]): Unit = {
val host = args(0)
val port = args(1).toInt
val masterHost = args(2)
val masterPort = args(3).toInt
val memory = args(4).toInt
val cores = args(5).toInt
//准备配置
val configStr=
s"""
|akka.actor.provider = "akka.remote.RemoteActorRefProvider" |akka.remote.netty.tcp.hostname = "$host"
|akka.remote.netty.tcp.port = "$port" """.stripMargin
val config = ConfigFactory.parseString(configStr)
val actorSystem = ActorSystem("WorkerSystem",config)
actorSystem.actorOf(Props(new Worker(masterHost,masterPort,memory,cores)),"Worker")
actorSystem.registerOnTermination()
}
}
package cn.itcast.rpc
/**
* Created by root on 2016/5/13. */
trait RemoteMessage extends Serializable
//Worker -> Master case class RegisterWorker(id: String, memory: Int, cores: Int) extends RemoteMessage
case class Heartbeat(id: String) extends RemoteMessage
//Master -> Worker case class RegisteredWorker(masterUrl: String) extends RemoteMessage
//Worker -> self case object SendHeartbeat
// Master -> self case object CheckTimeOutWorker
package cn.itcast.rpc
/**
* Created by root on 2016/5/13. */
class WorkerInfo(val id: String, val memory: Int, val cores: Int) {
//TODO 上一次心跳
var lastHeartbeatTime : Long = _
}
开始注册 9fffc07c-cbec-4740-ad19-5d553bc7b42d
接受心跳
接受心跳
接受心跳
接受心跳
接受心跳
[WARN] [11/02/2018 11:56:13.513] [New I/O worker #5] [NettyTransport(akka://MasterSystem)] Remote connection to [/192.168.5.1:56987] failed with java.io.IOException: 远程主机强迫关闭了一个现有的连接。
[WARN] [11/02/2018 11:56:13.514] [MasterSystem-akka.remote.default-remote-dispatcher-5] [akka.tcp://[email protected]:9999/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2FWorkerSystem%40192.168.5.1%3A8888-1] Association with remote system [akka.tcp://[email protected]:8888] has failed, address is now gated for [5000] ms. Reason: [Disassociated]
去除掉失去心跳的worker 9fffc07c-cbec-4740-ad19-5d553bc7b42d