Skip to content

Instantly share code, notes, and snippets.

Avatar
🏠
Working from home

Debasish Ghosh debasishg

🏠
Working from home
View GitHub Profile
View pubsub.scala
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")
View Pub.scala
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)
}
}
View Publisher.scala
class Publisher(client: RedisClient) extends Actor {
def receive = {
case Publish(channel, message) =>
client.publish(channel, message)
reply(true)
}
}
View Sub.scala
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)
}
View PubSubMessage.scala
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
View callback.scala
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
View gist:370023
1. Download redis from http://github.com/antirez/redis
2. build using "make"
3. Run server as ./redis-server
View gist:370028
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"
View gist:370030
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
View gist:370031
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