Last active
April 1, 2016 04:32
-
-
Save simerplaha/122975790aca877e287e to your computer and use it in GitHub Desktop.
Akka event bus simple publisher/subscriber code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import akka.actor._ | |
import akka.event.{EventBus, SubchannelClassification} | |
import akka.util.Subclassification | |
object SCEventBus extends EventBus with SubchannelClassification { | |
type Event = (String, Any, ActorRef) | |
type Classifier = String | |
type Subscriber = ActorRef | |
override protected def classify(event: Event): Classifier = event._1 | |
protected def subclassification = new Subclassification[Classifier] { | |
def isEqual(x: Classifier, y: Classifier) = x == y | |
def isSubclass(x: Classifier, y: Classifier) = x.startsWith(y) | |
} | |
override protected def publish(event: Event, subscriber: Subscriber): Unit = | |
subscriber.tell(event._2, event._3) | |
} | |
class Subscriber extends Actor { | |
override def receive: Actor.Receive = { | |
case (payload: Any) => | |
println(s"Subscriber: $sender -> $payload") | |
} | |
} | |
class Publisher extends Actor { | |
override def receive: Actor.Receive = { | |
case (payload: Any) => | |
println(s"Publisher: $sender -> $payload") | |
} | |
} | |
object Main extends App { | |
val system = ActorSystem() | |
// create subscribers | |
val rootSubscriber = system.actorOf(Props[Subscriber], "rootSubscriber") | |
val eventSubscriber = system.actorOf(Props[Subscriber], "eventSubscriber") | |
val itemSubscriber = system.actorOf(Props[Subscriber], "itemSubscriber") | |
// set up subscriptions | |
SCEventBus.subscribe(rootSubscriber, "/") | |
SCEventBus.subscribe(eventSubscriber, "/event") | |
SCEventBus.subscribe(itemSubscriber, "/event/42") | |
// create event publisher | |
val eventPublisher = system.actorOf(Props[Publisher], "eventPublisher") | |
// generate some events | |
SCEventBus.publish(("/", "payload A", eventPublisher)) | |
SCEventBus.publish(("/event", "payload B", eventPublisher)) | |
SCEventBus.publish(("/event/42", "payload C", eventPublisher)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment