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"));