66 lines
2.0 KiB
C#
66 lines
2.0 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using NLog;
|
|
using StackExchange.Redis;
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace EgwCoreLib.Lux.Data.Services
|
|
{
|
|
public class RedisSubscriptionManager
|
|
{
|
|
#region Public Constructors
|
|
|
|
public RedisSubscriptionManager(IConnectionMultiplexer connection)
|
|
{
|
|
_subscriber = connection.GetSubscriber();
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Methods
|
|
|
|
public IEnumerable<string> GetActiveChannels() => _subscriptions.Keys;
|
|
|
|
public bool Subscribe(string channel, Action<RedisChannel, RedisValue> handler)
|
|
{
|
|
if (_subscriptions.ContainsKey(channel))
|
|
return false;
|
|
|
|
RedisChannel rChannel = new RedisChannel(channel, RedisChannel.PatternMode.Literal);
|
|
var task = _subscriber.SubscribeAsync(rChannel, handler);
|
|
_subscriptions[channel] = new ChannelSubscription(channel, handler);
|
|
Log.Info($"✅ Subscribed to channel: {channel}");
|
|
|
|
return true;
|
|
}
|
|
|
|
public bool Unsubscribe(string channel)
|
|
{
|
|
if (!_subscriptions.TryRemove(channel, out var sub))
|
|
return false;
|
|
|
|
RedisChannel rChannel = new RedisChannel(channel, RedisChannel.PatternMode.Literal);
|
|
_subscriber.Unsubscribe(rChannel, sub.Handler);
|
|
Log.Info($"❌ Unsubscribed from channel: {channel}");
|
|
|
|
return true;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
|
|
#region Private Fields
|
|
|
|
private static Logger Log = LogManager.GetCurrentClassLogger();
|
|
private readonly ISubscriber _subscriber;
|
|
|
|
private readonly ConcurrentDictionary<string, ChannelSubscription> _subscriptions = new();
|
|
|
|
#endregion Private Fields
|
|
}
|
|
|
|
public record ChannelSubscription(string Channel, Action<RedisChannel, RedisValue> Handler);
|
|
} |