Skip to content

Instantly share code, notes, and snippets.

@dsarfati
Last active February 18, 2016 16:51
Show Gist options
  • Save dsarfati/816715d6f80597575e19 to your computer and use it in GitHub Desktop.
Save dsarfati/816715d6f80597575e19 to your computer and use it in GitHub Desktop.
Akka Pub/Sub Extensions

Simple helper classes that allow Akka Actors to publish and subscribe to a DistributedPubSub system by automatically determining the "topic" name from the class name.

import akka.actor.Actor
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.Publish
import scala.reflect.runtime.universe._
/** Actor that can publish data */
trait Publisher extends Actor {
//PubSub for the current actor system
private val pubsub = DistributedPubSub(context.system).mediator
/**
* Send data for the given type of data
*
* @param msg Message to send
* @tparam A Type of message, used as the message topic
*/
protected def publish[A: TypeTag](msg: A) = pubsub ! Publish(typeOf[A].getClass.getName, msg)
}
import akka.actor.Actor
import akka.cluster.pubsub.DistributedPubSub
import akka.cluster.pubsub.DistributedPubSubMediator.Subscribe
import scala.reflect.runtime.universe._
/** Actor that can subscribe to the pipes */
trait Subscriber extends Actor {
//PubSub for the current actor system
private lazy val pubsub = DistributedPubSub(context.system).mediator
/**
* Subscribe for the given type of data
*
* @tparam A Type that you are interested in receiving
*/
protected def subscribe[A]()(implicit tag: TypeTag[A]): Unit = pubsub ! Subscribe(typeOf[A].getClass.getName, self)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment