sql >> Base de Datos >  >> NoSQL >> Redis

Servidor Pub/Sub administrado de Redis

El motor Pub/Sub que impulsa Redis ServerEvents y Redis MQ se extrajo y encapsuló en una clase reutilizable que se puede usar de forma independiente para manejar mensajes publicados en canales específicos de Redis Pub/Sub.

RedisPubSubServer procesa los mensajes en un hilo de fondo administrado que reconecta automáticamente cuando la conexión del servidor redis falla y funciona como un servicio independiente en segundo plano que se puede detener e iniciar a pedido.

La API pública se captura en la interfaz IRedisPubSubServer:

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<string, string> OnMessage { get; set; }
    // Fired after successfully subscribing to the specified channels
    Action<string> OnUnSubscribe { get; set; }
    // Called when an exception occurs 
    Action<Exception> OnError { get; set; }
    // Called before attempting to Failover to a new redis master
    Action<IRedisPubSubServer> 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();
}

Número de uso

Para usar RedisPubSubServer , inicialícelo con los canales a los que desea suscribirse y asigne controladores para cada uno de los eventos que desea manejar. Como mínimo querrá manejar OnMessage :

var clientsManager = new PooledRedisClientManager();
var redisPubSub = new RedisPubSubServer(clientsManager, "channel-1", "channel-2") {
        OnMessage = (channel, msg) => "Received '{0}' from '{1}'".Print(msg, channel)
    }.Start();

Llamando a Start() después de que se inicialice, comenzará a escuchar y procesar cualquier mensaje publicado en los canales suscritos.