java akka_AKKA上手(基于Java)

本文介绍了Akka,一个用于构建高并发、分布式、容错的事件驱动应用的工具,重点讨论了Actor的概念、消息传递机制、模块化依赖以及通过Java实现的一个简单示例,展示了如何创建和进行Actor间的异步通信。
摘要由CSDN通过智能技术生成

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 可以如下方式构建一个简单的工程:

060e9aee6d05

image.png

我们可以用Eclipse以maven工程方式导入它:

060e9aee6d05

image.png

如下运行:

060e9aee6d05

image.png

2.2 代码介绍:

Sequence示意图图下:

060e9aee6d05

image.png

2.2.1 两种Actor(及通信的消息)的定义

060e9aee6d05

image.png

060e9aee6d05

image.png

2.2.2 创建Actor实例

060e9aee6d05

image.png

2.2.3 Actor间异步通信

一个Actor只有当它收到消息时才会去做一些事情,the sender 把消息放到接收者的mailbox中,然后自己去做别的事情。一个Actor的mailbox能保证同一个sender发过来的消息的相对先后顺序,但不一定连续,因为中间可能会穿插有另外一些Actor发过来的消息。

060e9aee6d05

image.png

060e9aee6d05

image.png

2.3 测试Actor:

060e9aee6d05

image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值