用scalaJ简单实现RPC

idea maven3.0 scala1.0

两个模块 Master Worker

idea 运行
运行master 
        ip(自己电脑的ip)  8888(master指定一个随意的端口号)
运行worker 
ip(自己电脑的ip)  9000(worker随意的端口号不能喝master重复)
ip(自己电脑的ip)  8888(master指定一个随意的端口号)
控制台打印
Master
constructor invoked 
preStart invoked
hello
 a client connected 

Worker
a reply form master
成功!!!!!!! 
package cn.lhh.rpc

import akka.actor.{Actor, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

/**
  * @author by lhh 
  */
class Master extends Actor{
  println("constructor invoked ")

  override def preStart(): Unit = {
    println("preStart invoked")
  }

  //接收消息的方法
  override def receive: Receive = {
    case "connect" => {
      println(" a client connected ")
      sender ! "reply"
    }
    case "hello" =>{
      println("hello")
    }
  }
}

object Master {
  def main(args: Array[String]): Unit = {
    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[Master],"Master")
    //发送消息
    master ! "hello"
    actorSystem.awaitTermination()//进程等待 不结束
  }
}
package cn.lhh.rpc

import akka.actor.{Actor, ActorSelection, ActorSystem, Props}
import com.typesafe.config.ConfigFactory

/**
  * @author by lhh 
  */

//把masterHost和masterPort传递进来
class Worker(val masterHost:String ,val masterPort: Int) extends Actor{
  //定义一个变量接收master
  var master : ActorSelection = _

  //创建和别的Actor的连接
  override def preStart(): Unit = {
    //在master启动的时候会打印下面的那个协议,可以先用这个做个标志,连接那个master
    //继承actor后会有一个context,用它来进行连接
    master = context.actorSelection(s"akka.tcp://MasterSystem@$masterHost:$masterPort/user/Master")
    master ! "connect"
  }

  override def receive: Receive = {
    case "reply"=>{
      println("a reply form master")
    }
  }
}

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 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)),"Worker")
    actorSystem.awaitTermination()
  }
}

你可能感兴趣的:(scala)