当前位置:首页 > 开发 > 开源软件 > 正文

【Akka一】Akka入门

发表于: 2015-02-28   作者:bit1129   来源:转载   浏览:
摘要: 什么是Akka Message-Driven Runtime is the Foundation to Reactive Applications In Akka, your business logic is driven through message-based communication patterns that are independent of physical locatio

什么是Akka

Message-Driven Runtime is the Foundation to Reactive Applications

In Akka, your business logic is driven through message-based communication patterns that are independent of physical locations. Whether your Actors live on the same thread, a different machine, or a different datacenter—the semantics are the same. You focus on the business logic while Akka handles the lower level plumbing to give your applications Reactive characteristics:

Resilience.
Resilience is a core tenet of Reactive applications, yet is often the most overlooked. With Akka, you get resilience for free as part of the model. Akka provides fault-tolerance based on supervisor hierarchies. Every Actor can create other Actors, which it will then supervise, making decisions if they should be resumed, restarted, retired or if the problem should be escalated. Instead of trying all things possible to prevent an error from happening, this approach lets you embrace the reality of unplanned errors. It means you can adopt a pragmatic ‘Let It Crash’ philosophy, with the confidence that the impacted components will be reset to a stable state and restarted upon failure.

Simpler Concurrency
Threads and non-blocking I/O are complex and error-prone to build by hand, which means they waste your time. With Akka's implementation of the Actor concurrency model, you are freed to focus on your application's business logic and let Akka think about scaling up.

Scalability and Elasticity
Scale out on multicore servers and multiple nodes using Akka makes application elasticity and true scale on demand a reality. On commodity hardware, you might run several million Actors—a huge step up from mere thousands of threads in a traditional Java application.

Scala & Java APIs
In keeping with the pragmatism of the rest of the Typesafe Reactive Platform, Akka has a APIs for both Java and Scala. This means smooth interoperability, and no need to learn or adopt Scala at all. Akka can run standalone on a JVM or deployed in your existing Java Application Server

 

 

 

In Akka, a Future is a data structure used to retrieve the result of some concurrent operation. This operation is usually performed by an Actor or by the Dispatcher directly. This result can be accessed synchronously (blocking) or asynchronously (non-blocking).

 

开发环境:

1. Intellij Idea创建Scala项目,此时默认添加了Scala Library

2. 添加Akka依赖:

http://central.maven.org/maven2/com/typesafe/akka/akka-actor_2.10/2.3.9/akka-actor_2.10-2.3.9.jar

http://central.maven.org/maven2/com/typesafe/config/1.2.1/config-1.2.1.jar

 

 

 

Akka Actor间异步通信

package akka.examples

import akka.actor.{ActorSystem, Props, Actor}

case object Goodbye

class HelloActor(name: String) extends Actor {
  def receive = {
    case "Hello" => println("Hello from %s".format(name))
    case Goodbye => println("Goodbye")
    case _ => println("%s, huh?".format(name))
  }
}

object HelloAkka {
  def main(args: Array[String]) {
    val system = ActorSystem("HelloSystem")
    // 如果HelloActor不带构造参数,这可以这么使用
    // val helloActor = system.actorOf(Props[HelloActor], name = "helloactor")
    // HelloActor带构造参数的
    val actor = system.actorOf(Props(new HelloActor("Jimmy")), name = "helloactor")
    actor ! "Hello"
    actor ! Goodbye
  }
}

 

 

Akka Actor间同步通信

package akka.examples

import java.util.concurrent.TimeoutException

import akka.actor._
import akka.actor.{Props, ActorSystem, Actor}
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._

import scala.concurrent.Await
import scala.concurrent.Future

case object Who

case object AnswerTimeout

class AnswerActor extends Actor {
  override def receive: Receive = {
    case Who => sender ! "Tom"
    case AnswerTimeout => {
      Thread.sleep(1000 * 10);
      sender ! "Answer time out"
    }
    case _ => sender ! "Not supported question"
  }
}

object AkkaFuture {

  def main(args: Array[String]) {
    val system = ActorSystem("QASystem")
    val answerActor = system.actorOf(Props(new AnswerActor), name = "answerActor")


    //1. 使用?同步发送请求, future等待
    implicit val timeout = Timeout(5 seconds)
    val future1 = answerActor ? Who
    val r1 = Await.result(future1, timeout.duration).asInstanceOf[String]
    println(r1)

    //2. 同步请求超时
    val future2 = answerActor ? AnswerTimeout
    try {
      val r2 = Await.result(future2, timeout.duration).asInstanceOf[String]
      println(r2)
    } catch {
      case e: TimeoutException => println(e.getMessage)
    }

    //通过ask方法发送同步等待消息
    val future3: Future[String] = ask(answerActor, "RocketQuestion").mapTo[String]
    val result3 = Await.result(future3, 5 second)
    println(result3)

    system.shutdown()
  }
}

 

 

参考://http://doc.akka.io/docs/akka/snapshot/scala/futures.html#futures-scala

 

 

【Akka一】Akka入门

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
这个akka入门系列大量参考了akka文档。主要是翻译+自己的一些理解。这里对akka文档吐一下槽,它的文
Akka 是一个用 Scala 编写的库,用于简化编写容错的、高可伸缩性的 Java 和 Scala 的 Actor 模型应
先从AKKA官网下载Typesafe Activator 我这里因为是mac所以会以mac系统做记录。 常规步骤: 1,下载
转载请注明出处: http://blog.csdn.net/jmppok/article/details/17264495 本文结合网上一些资料,
转载请注明出处:http://blog.csdn.net/jmppok/article/details/17264495 本文结合网上一些资料,对
Akka 异步处理框架,自己Google 前期准备: idea12(http://www.jetbrains.com/idea/) 在插件库中
转载请注明出处:http://blog.csdn.net/jmppok/article/details/17264495 本文结合网上一些资料,对
从第一篇Akka笔记的介绍中,我们是从很高的高度去观察Akka工具箱中的Actors。在这篇笔记的第二篇,
Actor的生命周期 在Actor系统中的路径代表一个“地方”,这可能被一个存活着的的actor占用着。最初
原文在http://rerun.me/2014/10/06/akka-notes-actorsystem-in-progress/ 像我们前面看到的,我们可
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号