事件機制就用於當前運行環境,與集羣環境不一樣,詳細見AKKA 集羣中的發佈與訂閱Distributed Publish Subscribe in Clusterhtml
簡單實現示例java
package event import akka.actor.AbstractActor import akka.actor.ActorRef import akka.actor.ActorSystem import akka.actor.Props import akka.event.japi.LookupEventBus import akka.japi.pf.ReceiveBuilder import com.typesafe.config.ConfigFactory /** * Created by: tankx * Date: 2019/7/18 * Description: 事件與監聽 */ object EventBus : LookupEventBus<MyEvent, ActorRef, String>() {//參數(事件類型,訂閱者類型,用於區分事件定義的類型) override fun classify(event: MyEvent): String {//用於區分不一樣事件(事件類型) return event.type } override fun publish(event: MyEvent, subscriber: ActorRef) { subscriber.tell(event, ActorRef.noSender()) } //指望的事件類型的數量 override fun mapSize(): Int { return 1000 } override fun compareSubscribers(a: ActorRef, b: ActorRef): Int { return a.compareTo(b) } } //訂閱actor class SubActor : AbstractActor() { override fun createReceive(): Receive { return ReceiveBuilder.create().matchAny(this::receive).build() } fun receive(msg: Any) { println("收到消息: $msg") } } fun main() { var system: ActorSystem = ActorSystem.create("system"); var eventActor = system.actorOf(Props.create(SubActor::class.java)) EventBus.subscribe(eventActor, "aaa")//(訂閱者,事件類型) EventBus.subscribe(eventActor, "bbb") EventBus.subscribe(eventActor, "ccc") EventBus.subscribe(eventActor, "ddd") EventBus.publish(MyEvent("aaa", "數據")) EventBus.publish(MyEvent("bbb", "數據")) EventBus.publish(MyEvent("ccc", "數據")) EventBus.publish(MyEvent("ccc", "數據")) }