杂谈 akka vertx 简单对比

vertx 文章引子,不使用配置和集群,简单对比akka与vertx的基础特性 以及 两者的Actor模型区别

Akka

  • ActorSystem
  val system = ActorSystem("jiaotengSystem")
  • Actors
class JActor1 extends Actor {
  override def receive = {}
}
  • actorOf
  val boot = system.actorOf(Props[JActor1], "jActor1")
  • 消息发送
case class ActorMsg(content: String)

class JActor1 extends Actor with ActorLogging {
  override def receive = {
    case "start" =>
      log.info("start")
      context.actorOf(Props[JActor2]) ! ActorMsg("hello , i am actor1")

    case ActorMsg(content) => log.info(content)
  }
}

class JActor2 extends Actor with ActorLogging {
  override def receive = {
    case ActorMsg(content) =>
      log.info(content)
      sender() ! ActorMsg("i am actor2 ")
  }
}
  • Akka-Http
  implicit val system = ActorSystem("jiaoteng-system")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  val route:Route =
    path("/hello") {
      get {
        complete(HttpEntity(ContentTypes.`application/json`, "{\"code\": 0}"))
      }
  }
  Http().bindAndHandle(route, "localhost", 8080)

Vertx

  • Vertx
 val vertx = Vertx.vertx()
  • Verticle
class JVerticle extends ScalaVerticle {
  override def start(): Unit = {}
}
  • deploy
vertx.deployVerticle(ScalaVerticle.nameForVerticle[JVerticle])
  • EventBus

  val eventBus = vertx.eventBus()
  // consumer
  eventBus.consumer[String]("test.address").handler(mes => {
      println(s"接收到的message:${mes.body()}")
      mes.reply("响应数据")
  })

  // sender
  val sendFuture = eventBus.sendFuture[String]("test.address", "message")
  sendFuture.map {
      res => println(s"响应的内容:${res.body()}")
  } recover {
      case e: Throwable => e.printStackTrace()
  }
  • Vertx-HttpServer
  val router = Router.router(vertx)
  vertx.createHttpServer().requestHandler(req => router.accept(req)).listen(8080)
  router.get("/hello").handler(routingContext => {
    routingContext.response().putHeader("Content-Type", "application/json").end("{\"code\": 0}")
  })

你可能感兴趣的:(杂谈 akka vertx 简单对比)