一、RPC简介
二、代码框架
三、代码实现
该小项目包含四个文件:
1.WorkerInfo,用于保存Worker的信息,此次保存Worker的上一次心跳时间
package com.zxl.rpc
class WorkerInfo(val id: String, val memory: Int, val cores: Int) {
// TODO 上一次心跳
var lastHeartbeatTime: Long = _
}
2.RemoteMessage,实现序列化并定义Master与Worker之间传送信息的类型
package com.zxl.rpc
/**
* 用于实现序列化 网络传输
*/
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
3.Worker,与Master进行消息交互
package com.zxl.rpc
import java.util.UUID
import akka.actor.{Props, ActorSystem, Actor, ActorSelection}
import com.typesafe.config.ConfigFactory
import scala.concurrent.duration._
class Worker(val masterHost: String, val masterPort: Int, val memory: Int, val cores: Int) extends Actor {
// 与master连接的对象
var master : ActorSelection = _
// 每个worker的id
val workerId = UUID.randomUUID().toString
// 发送心跳的时间间隔
val HEART_INTERVAL = 10000
override def preStart(): Unit = {
// 建立连接
// 在Master启动时会打印下面的那个协议, 可以先用这个做一个标志, 连接哪个master
// 继承actor后会有一个context, 可以通过它来连接
// 需要有/user, Master要和master那边创建的名字保持一致
master = context.actorSelection(s"akka.tcp://MasterSystem@$masterHost:$masterPort/user/Master")
// 向Master发送注册消息
master ! RegisterWorker(workerId, memory, cores)
}
override def receive: Receive = {
case RegisteredWorker(masterUrl) => {
println(masterUrl)
// 启动定时器发送心跳
import context.dispatcher
// 多长时间后执行 单位,多长时间执行一次 单位, 消息的接受者(直接给master发不好, 先给自己发送消息, 以后可以做下判断, 什么情况下再发送消息), 信息
context.system.scheduler.schedule(0 millis, HEART_INTERVAL millis, self, SendHeartbeat)
}
case SendHeartbeat => {
println("send heartbeat to master")
// 对master发送心跳信息,发送当前worker的id
master ! Heartbeat(workerId)
}
}
}
object Worker {
def main(args: Array[String]) {
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)
// ActorSystem老大,辅助创建和监控下面的Actor,它是单例的
val actorSystem = ActorSystem("WorkerSystem", config)
actorSystem.actorOf(Props(new Worker(masterHost, masterPort, memory, cores)), "Worker")
actorSystem.awaitTermination()
}
}
4.Master,接收Worker的消息并做回应
package com.zxl.rpc
import akka.actor.{Props, ActorSystem, Actor}
import com.typesafe.config.ConfigFactory
import scala.collection.mutable
import scala.concurrent.duration._
class Master(val host: String, val port: Int) extends Actor {
// 保存(workerId,WorkerInfo)
val idToWorker = new mutable.HashMap[String, WorkerInfo]()
// 保存wokerInfo
// 使用set删除快, 也可用linkList
val workers = new mutable.HashSet[WorkerInfo]()
// 超时检查的间隔
val CHECK_INTERVAL = 15000
override def preStart(): Unit = {
println("preStart invoked")
// 导入隐式转换
import context.dispatcher
// 使用timer太low了, 可以使用akka的, 使用定时器, 要导入这个包
// 定时检查worker的心跳时间是否超时
context.system.scheduler.schedule(0 millis, CHECK_INTERVAL millis, self, CheckTimeOutWorker)
}
// 用于接收消息
override def receive: Receive = {
case RegisterWorker(id, memory, cores) => {
// 判断一下,是不是已经注册过
if(!idToWorker.contains(id)) {
// 把Worker的信息封装起来保存到内存当中
val workerInfo = new WorkerInfo(id, memory, cores)
idToWorker(id) = workerInfo
workers += workerInfo
// 通知worker注册 并将master的地址返回给worker
sender ! RegisteredWorker(s"akka.tcp://MasterSystem@$host:$port/user/Master")
}
}
case Heartbeat(id) => {
if(idToWorker.contains(id)) {
val workerInfo = idToWorker(id)
// 报活
val currentTime = System.currentTimeMillis()
// 更新已收到id的worker的上一次心跳时间
workerInfo.lastHeartbeatTime = currentTime
}
}
case CheckTimeOutWorker => {
val currentTime = System.currentTimeMillis()
// 获取过时的worker
val toRemove = workers.filter(x => currentTime - x.lastHeartbeatTime > CHECK_INTERVAL)
// 将超时的worker从两个集合中去掉
for(w <- toRemove) {
workers -= w
idToWorker -= w.id
}
println(workers.size)
}
}
}
object Master {
def main(args: Array[String]) {
val host = args(0)
val port = args(1).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)
// ActorSystem老大,辅助创建和监控下面的Actor,它是单例的
val actorSystem = ActorSystem("MasterSystem", config)
// 创建Actor
val master = actorSystem.actorOf(Props(new Master(host, port)), "Master")
master ! "hello"
actorSystem.awaitTermination()
}
}