Pub-Sub
This page describes how to do Pub/Sub with scredis.
Publishing
To publish messages, you can use the Redis instance or the regular non-blocking Client.
import scredis._
import scala.util.{ Success, Failure }
// Creates a Redis instance with default configuration (see reference.conf)
val redis = Redis()
// Import the intenral ActorSystem's dispatcher (execution context) to register callbacks
import redis.dispatcher
// Send a GET request and register a callback
redis.publish("channel", "foo").onComplete {
case Success(count) => // the message was published to 'count' client
case Failure(e) => // an error occurred while publishing the message 'foo' to channel 'channel'
}
Subscribing
To subscribe to messages and events, you must use a SubscriberClient
. You can either create one or use the lazily initialized one present in a Redis
instance.
The SubscriberClient
requires a scredis.Subscription
which simply denotes a function of scredis.PubSubMessage
to Any
. When you use SubscriberClient
from Redis instance then a scredis.Subscription
handler is taken from Redis
instance.
type Subscription = Function[scredis.PubSubMessage, Any]
The complete list of scredis.PubSubMessage
can be found here.
import scredis.PubSubMessage
private val subscriptionHandler: Function[PubSubMessage, Unit] = {
case m: PubSubMessage.Subscribe => println(s"Subscribed to channel ${m.channel}")
case m: PubSubMessage.Message => println(s"Received message for channel ${m.channel} with data ${m.readAs[String]()}")
case m: PubSubMessage.Unsubscribe => println(s"Unsubscribed from channel ${m.channelOpt}")
case m: PubSubMessage.PSubscribe => println(s"Subscribed to channels matching pattern ${m.pattern}")
case m: PubSubMessage.PMessage => println(s"Received message for pattern ${m.pattern} on channel ${m.channel} with data ${m.readAs[String]()}")
case m: PubSubMessage.PUnsubscribe => println(s"Unsubscribed from pattern matching ${m.patternOpt}")
case e: PubSubMessage.Error => println(s"Scredis received error $e")
}
// Creates a Redis instance with default configuration.
// Provide custom function handling pub/sub related events
val redis = scredis.Redis(subscription = subscriptionHandler)
// Subscribe to 'channel1' and 'channel2'
val subscribeF: Future[Int] = redis.subscriber.subscribe("channel1", "channel2")
// subscribeF will evaluate to 2
The source code for this page can be found here.