欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Akka简单案例(1)

程序员文章站 2024-02-19 13:53:58
...

一、pom依赖

      <!-- 添加akka的actor依赖 -->
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-actor_2.11</artifactId>
            <version>2.4.17</version>
        </dependency>

        <!-- 多进程之间的Actor通信 -->
        <dependency>
            <groupId>com.typesafe.akka</groupId>
            <artifactId>akka-remote_2.11</artifactId>
            <version>2.4.17</version>
        </dependency>

二、SenderActor

import akka.actor.Actor

object SenderActor extends Actor {
  override def receive: Receive = {
    case "start" => {
      println("SenderActor: 接收到start消息")
      //发送一个submitTaskMessage消息给ReceiverActor
      // path 地址本地actor地址
      //akka://actorSystem定义的名字/user/actor的名字
      val receiverActor = context.actorSelection(path = "akka://actorSystem/user/receiverActor")
      //发送消息
      receiverActor ! SubmitTaskMessage("提交任务")
    }
    case SuccessSubmitTaskMessage(message) => {
      println(s"SenderActor接收到 ${message}")
    }
  }
}

三、receiverActor

import akka.actor.Actor


object ReceiverActor extends Actor {
  override def receive: Receive = {
    case SubmitTaskMessage(message) => {
      println(s"ReceiverActor:${message}")
      //回复一个消息给SenderActor sender引用消息发送者回复
      sender ! SuccessSubmitTaskMessage("成功提交任务")
    }
  }
}

四、MessageDefinition

//消息封装样例类
case class SubmitTaskMessage(message: String)

case class SuccessSubmitTaskMessage(message: String)

五、Entrance

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

object Entrance {
  def main(args: Array[String]): Unit = {
    // 实现Acotr trait
    // 创建actorSystem
    val actorSystem = ActorSystem("actorSystem", ConfigFactory.load())
    // 加载 Actor
    val sendActor = actorSystem.actorOf(Props(SenderActor), "sendActor")
    val receiverActor = actorSystem.actorOf(Props(ReceiverActor), "receiverActor")
    sendActor ! "start"

  }
}

运行结果:
SenderActor: 接收到start消息
ReceiverActor:提交任务
SenderActor接收到 成功提交任务