day29akka
PS:AKKA
之前要实现并发编程,通常要借用netty框架,现在如果又要高并发又要分布式就使用akka框架
这个akka在客户端和服务端每一端都相当于一个actor,尤其是服务端需要一个总管进行管理
PS: RPC
不同进程之间的的方法调用
-----------------------------实现项目
1.创建Maven项目
PS:通常编译好的话,使用插件的package命令导包,放大linux执行。
PS : Master
import akka.actor.{Actor, ActorSystem, Props} import com.typesafe.config.ConfigFactory import scala.collection.mutable import scala.concurrent.duration._ class Master extends Actor{ println("constructor invoked") override def preStart(): Unit = { println("prStart invoked") } //用于接收消息 override def receive: Receive = { case "connect" =>{ println("a client invoked") sender ! "reply" } case "hello" =>{ println("hello") } } } object Master{ def main(args: Array[String]){ val host = "192.168.93.217" val port = 8888 // 准备配置 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), "Master") master !"hello" actorSystem.awaitTermination() } }
PS:Worker
import akka.actor.Actor import java.util.UUID import akka.actor.{Actor, ActorSelection, ActorSystem, Props} import com.typesafe.config.ConfigFactory import scala.concurrent.duration._ class Worker extends Actor{ var master : ActorSelection = _ //建立连接 override def preStart(): Unit = { //println("prStart invoked") //跟Master建立连接 master = context.actorSelection(s"akka.tcp://MasterSystem@192.168.93.217:8888/user/Master") //向Master发送注册消息 master ! "connect" } //用于接收消息 override def receive: Receive = { case "reply" =>{ println("a reply from master") } /*case "hello" =>{ println("hello") }*/ } } object Worker{ def main(args: Array[String]){ val host = "192.168.93.217" val port = 9999 //端口要修改 // 准备配置 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) //创建Actor actorSystem.actorOf(Props[Worker], "Worker") actorSystem.awaitTermination() } }
------------------------------------------------------------------------下午没学
posted on 2018-03-27 16:16 biyangqiang 阅读(106) 评论(0) 编辑 收藏 举报