AKKA event mechanism

AKKA Event Bus

Mechanism for events on the current operating environment, with different cluster environment, see detailed AKKA cluster publish and subscribe Distributed Publish Subscribe in Cluster

Simple implementation example

Package Penalty for 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 

/ ** 
 * the Created by: tankx 
 * a Date: 2019/7/18 
 * the Description: events and listeners 
 * / 
Object EventBus: LookupEventBus <MyEvent, ActorRef, String> () { // parameters (event type, subscriber type, with to distinguish the type of event definition) 

    the override Classify Fun (event: the MyEvent): String { // used to distinguish between different events (event type) 
        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 (the MyEvent ( ))"BBB", "data"
    EventBus.publish (the MyEvent ( "CCC", "data" )) 
    EventBus.publish (the MyEvent ( "CCC", "data" )) 
}

 

Guess you like

Origin www.cnblogs.com/tankaixiong/p/11209962.html