--- slug: pubsub title: Redis Managed Pub/Sub Server --- The Pub/Sub engine powering [Redis ServerEvents](/redis-server-events) and [Redis MQ](/redis-mq) has been extracted and encapsulated it into a re-usable class that can be used independently for handling messages published to specific [Redis Pub/Sub](http://redis.io/commands#pubsub) channels. `RedisPubSubServer` processes messages in a managed background thread that **automatically reconnects** when the redis-server connection fails and works like an independent background Service that can be stopped and started on command. ## API The public API is captured in the [IRedisPubSubServer](https://github.com/ServiceStack/ServiceStack/blob/master/src/ServiceStack.Interfaces/Redis/IRedisPubSubServer.cs) interface: ```csharp public interface IRedisPubSubServer : IDisposable { IRedisClientsManager ClientsManager { get; } // What Channels it's subscribed to string[] Channels { get; } // Run once on initial StartUp Action OnInit { get; set; } // Called each time a new Connection is Started Action OnStart { get; set; } // Invoked when Connection is broken or Stopped Action OnStop { get; set; } // Invoked after Dispose() Action OnDispose { get; set; } // Fired when each message is received Action OnMessage { get; set; } // Fired after successfully subscribing to the specified channels Action OnUnSubscribe { get; set; } // Called when an exception occurs Action OnError { get; set; } // Called before attempting to Failover to a new redis master Action OnFailover { get; set; } int? KeepAliveRetryAfterMs { get; set; } // The Current Time for RedisServer DateTime CurrentServerTime { get; } // Current Status: Starting, Started, Stopping, Stopped, Disposed string GetStatus(); // Different life-cycle stats string GetStatsDescription(); // Subscribe to specified Channels and listening for new messages IRedisPubSubServer Start(); // Close active Connection and stop running background thread void Stop(); // Stop than Start void Restart(); } ``` ## Usage To use `RedisPubSubServer`, initialize it with the channels you want to subscribe to and assign handlers for each of the events you want to handle. At a minimum you'll want to handle `OnMessage`: ```csharp var clientsManager = new PooledRedisClientManager(); var redisPubSub = new RedisPubSubServer(clientsManager, "channel-1", "channel-2") { OnMessage = (channel, msg) => "Received '{0}' from '{1}'".Print(msg, channel) }.Start(); ``` Calling `Start()` after it's initialized will get it to start listening and processing any messages published to the subscribed channels.