103 lines
2.6 KiB
C#
103 lines
2.6 KiB
C#
using StackExchange.Redis;
|
|
|
|
namespace MP.MONO.Data
|
|
{
|
|
public class MessagePipe
|
|
{
|
|
#region Private Fields
|
|
|
|
private IConnectionMultiplexer redis;
|
|
private bool enableConsoleLog = false;
|
|
|
|
#endregion Private Fields
|
|
|
|
#region Public Constructors
|
|
|
|
public MessagePipe(IConnectionMultiplexer redisConn, string channelName, bool enableLog = false)
|
|
{
|
|
_channel = channelName;
|
|
redis = redisConn;
|
|
enableConsoleLog = enableLog;
|
|
// aggiungo sottoscrittore
|
|
setupSubscriber();
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Events
|
|
|
|
public event EventHandler EA_NewMessage = delegate { };
|
|
|
|
#endregion Public Events
|
|
|
|
#region Private Properties
|
|
|
|
/// <summary>
|
|
/// Canale associato al gestore pipeline messaggi
|
|
/// </summary>
|
|
private string _channel { get; set; } = "";
|
|
|
|
#endregion Private Properties
|
|
|
|
#region Private Methods
|
|
|
|
private void setupSubscriber()
|
|
{
|
|
ISubscriber sub = redis.GetSubscriber();
|
|
//Subscribe to the channel named messages
|
|
sub.Subscribe(_channel, (channel, message) =>
|
|
{
|
|
// Se abilitato Output messaggio ricevuto
|
|
if (enableConsoleLog)
|
|
{
|
|
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {message}");
|
|
}
|
|
PubSubEventArgs mea = new PubSubEventArgs(message);
|
|
// se qualcuno ascolta sollevo evento nuovo valore...
|
|
if (EA_NewMessage != null)
|
|
{
|
|
EA_NewMessage(this, mea);
|
|
}
|
|
});
|
|
Console.WriteLine($"Subscribed {_channel}");
|
|
}
|
|
|
|
#endregion Private Methods
|
|
|
|
#region Public Methods
|
|
|
|
/// <summary>
|
|
/// Invio messaggio sul canale
|
|
/// </summary>
|
|
/// <param name="newMess"></param>
|
|
/// <returns></returns>
|
|
public bool sendMessage(string newMess)
|
|
{
|
|
bool answ = false;
|
|
|
|
ISubscriber sub = redis.GetSubscriber();
|
|
sub.Publish(_channel, newMess);
|
|
return answ;
|
|
}
|
|
|
|
#endregion Public Methods
|
|
}
|
|
|
|
public class PubSubEventArgs : EventArgs
|
|
{
|
|
#region Public Constructors
|
|
|
|
public PubSubEventArgs(string messaggio)
|
|
{
|
|
this.newMessage = messaggio;
|
|
}
|
|
|
|
#endregion Public Constructors
|
|
|
|
#region Public Properties
|
|
|
|
public string newMessage { get; set; } = "";
|
|
|
|
#endregion Public Properties
|
|
}
|
|
} |