AKKA事件机制

AKKA Event Bus

事件机制就用于当前运行环境,与集群环境不同,详细见AKKA 集群中的发布与订阅Distributed Publish Subscribe in Cluster

简单实现示例

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", "数据"))
}

 

posted @ 2019-07-18 21:02  itank  阅读(582)  评论(0编辑  收藏  举报