Skip to content

Instantly share code, notes, and snippets.

View debasishg's full-sized avatar
🏠
Working from home

Debasish Ghosh debasishg

🏠
Working from home
View GitHub Profile
val c1 = new PubSubClient("foo", r)
c1.start
val c2 = new PubSubClient("bar", t)
c2.start
val server = new PubSubServer
server.start
server ! Subscribe(c1, List("a", "b", "c"))
server ! Publish(c2, "a", "hello")
server ! Publish(c2, "c", "hi")
object Pub {
println("starting publishing service ..")
val p = new Publisher(new RedisClient("localhost", 6379))
p.start
def publish(channel: String, message: String) = {
p ! Publish(channel, message)
}
}
class Publisher(client: RedisClient) extends Actor {
def receive = {
case Publish(channel, message) =>
client.publish(channel, message)
reply(true)
}
}
object Sub {
println("starting subscription service ..")
val s = new Subscriber(new RedisClient("localhost", 6379))
s.start
s ! Register(callback)
def sub(channels: String*) = {
s ! Subscribe(channels.toArray)
}
sealed trait PubSubMessage
case class S(channel: String, noSubscribed: Int) extends PubSubMessage
case class U(channel: String, noSubscribed: Int) extends PubSubMessage
case class M(origChannel: String, message: String) extends PubSubMessage
def callback(pubsub: PubSubMessage) = pubsub match {
case S(channel, no) => println("subscribed to " + channel + " and count = " + no)
case U(channel, no) => println("unsubscribed from " + channel + " and count = " + no)
case M(channel, msg) =>
msg match {
// exit will unsubscribe from all channels and stop subscription service
case "exit" =>
println("unsubscribe all ..")
r.unsubscribe
1. Download redis from http://github.com/antirez/redis
2. build using "make"
3. Run server as ./redis-server
1. Open a shell and set AKKA_HOME to the distribution root
2. cd $AKKA_HOME
3. sbt console
4. scala> import sample.pubsub._
5. scala> Sub.sub("a", "b") // starts Subscription server & subscribes to channels "a" and "b"
1. Open up another shell similarly as the above and set AKKA_HOME
2. cd $AKKA_HOME
3. sbt console
4. scala> import sample.pubsub._
5. scala> Pub.publish("a", "hello") // the first shell should get the message
6. scala> Pub.publish("c", "hi") // the first shell should NOT get this message
Open up a redis-client from where you installed redis and issue a publish command
./redis-cli publish a "hi there" ## the first shell should get the message