Akka是一个工具集和运行时环境,可以构建基于JVM上的高并发、分布式、容错的事件驱动型应用。下面介绍几个术语:
Actor : the unit of execution in Akka
Messages: 可以是任意Object,boxed primitive values也可以 (比如 Integer, Boolean 等等)。由于Message要在不同线程中共享,所以应当设计成immutable
Event-driven model — Actors perform work in response to messages. Communication between Actors is asynchronous, allowing Actors to send messages and continue their own work without blocking to wait for a reply.
Strong isolation principles — Unlike regular objects in Java, an Actor does not have a public API in terms of methods that you can invoke. Instead, its public API is defined through messages that the actor handles. This prevents any sharing of state between Actors; the only way to observe another actor’s state is by sending it a message asking for it.(就是说公共API是通过消息传递实现的,而不是提供一个public方法给外面直接调用)
Location transparency — The system constructs Actors from a factory and returns references to the instances. Because location doesn’t matter, Actor instances can start, stop, move, and restart to scale up and down as well as recover from unexpected failures.(后面我们会看到我们生成的都是ActorRef,而不是Actor本身)
Lightweight — Each instance consumes only a few hundred bytes, which realistically allows millions of concurrent Actors to exist in a single application.(一个应用里面可以存在上百万Actor实例,你就放心的用吧)
Supervision only handles error scenarios — not graceful stopping
1, AKKA的各种modular所需要的Maven依赖
它可以分成很多Modular,所需的Maven依赖如下:
ACTOR library:
com.typesafe.akka
akka-actor_2.12
2.5.17
Remoting:
com.typesafe.akka
akka-remote_2.12
2.5.17
Cluster:
com.typesafe.akka
akka-cluster_2.12
2.5.17
Cluster Sharding:
com.typesafe.akka
akka-cluster-sharding_2.12
2.5.17
Cluster Singleton:
com.typesafe.akka
akka-cluster-singleton_2.12
2.5.17
Cluster Publish-Subscribe:
com.typesafe.akka
akka-cluster-tools_2.12
2.5.17
Persistence:
com.typesafe.akka
akka-persistence_2.12
2.5.17
Distributed Data:
com.typesafe.akka
akka-distributed-data_2.12
2.5.17
Streams:
com.typesafe.akka
akka-stream_2.12
2.5.17
2,一个例子
2.1 可以如下方式构建一个简单的工程:
image.png
我们可以用Eclipse以maven工程方式导入它:
image.png
如下运行:
image.png
2.2 代码介绍:
Sequence示意图图下:
image.png
2.2.1 两种Actor(及通信的消息)的定义
image.png
image.png
2.2.2 创建Actor实例
image.png
2.2.3 Actor间异步通信
一个Actor只有当它收到消息时才会去做一些事情,the sender 把消息放到接收者的mailbox中,然后自己去做别的事情。一个Actor的mailbox能保证同一个sender发过来的消息的相对先后顺序,但不一定连续,因为中间可能会穿插有另外一些Actor发过来的消息。
image.png
image.png
2.3 测试Actor:
image.png