AKKA入门教程----事件总线(发布订阅模式)

1、这种分类最初是专门为执行DeathWatch而开发的:订户和分类器都是类型的ActorRef。这种分类要求ActorSystem执行与作为参与者的订户有关的簿记操作,其可以在没有首先从EventBus取消订阅的情况下终止。ManagedActorClassification维护一个系统Actor,它负责自动处理取消订阅终止的actor。

订阅者可以订阅不同类型的事件,事件发送时,不同的接收者会接收到

 

ActorRef observer1 = new TestKit(system).getRef();ActorRef observer2 = new TestKit(system).getRef();TestKit probe1 = new TestKit(system);TestKit probe2 = new TestKit(system);ActorRef subscriber1 = probe1.getRef();ActorRef subscriber2 = probe2.getRef();ActorBusImpl actorBus = new ActorBusImpl(system);
actorBus.subscribe(subscriber1, observer1);
actorBus.subscribe(subscriber2, observer1);
actorBus.subscribe(subscriber2, observer2);Notification n1 = new Notification(observer1, 100);
actorBus.publish(n1);
probe1.expectMsgEquals(n1);
probe2.expectMsgEquals(n1);Notification n2 = new Notification(observer2, 101);
actorBus.publish(n2);
probe2.expectMsgEquals(n2);
probe1.expectNoMsg(FiniteDuration.create(500, TimeUnit.MILLISECONDS));
subscriber1 , subscriber2  订阅者订阅了  observer1 ,当actorBus 发送 observer1类型通知事件时-->subscriber1 ,subscriber2  都会收到

 

2、事件总线发布订阅、 事件流中实现了子通道分类,所以可以通过订阅它们的公共超类来订阅一组事件

interface AllKindsOfMusic { }

class Jazz implements AllKindsOfMusic {
final public String artist;
public Jazz(String artist) {
this.artist = artist;
}}class Electronic implements AllKindsOfMusic {
final public String artist;
public Electronic(String artist) {
this.artist = artist;
}}

static class Listener extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.match(Jazz.class, msg ->
System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg)
)
.match(Electronic.class, msg ->
System.out.printf("%s is listening to: %s%n", getSelf().path().name(), msg)
)
.build();
}}
final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class));
system.eventStream().subscribe(actor, DeadLetter.class);

final ActorRef jazzListener = system.actorOf(Props.create(Listener.class));
final ActorRef musicListener = system.actorOf(Props.create(Listener.class));
system.eventStream().subscribe(jazzListener, Jazz.class);
system.eventStream().subscribe(musicListener, AllKindsOfMusic.class);

// only musicListener gets this message, since it listens to *all* kinds of music:
system.eventStream().publish(new Electronic("Parov Stelar"));

// jazzListener and musicListener will be notified about Jazz:
system.eventStream().publish(new Jazz("Sonny Rollins"));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值