You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

98 lines
2.8 KiB
C#

using Microsoft.Extensions.Logging;
using ServiceStack.Messaging;
using ServiceStack.Redis;
using SlnMesnac.Config;
using StackExchange.Redis;
using System;
using System.Linq;
using System.Security.Cryptography;
#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* (c) 2024 WenJY
* CLR4.0.30319.42000
* LAPTOP-E0N2L34V
* SlnMesnac.Redis
* 98350fd3-5b25-4395-a2f0-eb949cc4c6f6
*
* WenJY
* wenjy@mesnac.com
* 2024-04-11 16:44:24
* V1.0.0
*
*
*--------------------------------------------------------------------
*
*
*
*
* V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Redis
{
/// <summary>
/// Redis
/// </summary>
public class RedisHandler
{
private ILogger<RedisHandler> _logger;
private readonly AppConfig _appConfig;
private readonly ISubscriber _subscriber;
private readonly ConnectionMultiplexer redis;
public RedisHandler(AppConfig appConfig, ILogger<RedisHandler> logger)
{
_appConfig = appConfig;
redis = ConnectionMultiplexer.Connect(_appConfig.redisConfig);
_subscriber = redis.GetSubscriber();
_logger = logger;
}
/// <summary>
/// 推送消息
/// </summary>
/// <param name="channel"></param>
/// <param name="message"></param>
public void PublishMessage(string channel, string message)
{
long res = _subscriber.Publish(channel, message);
_logger.LogInformation($"向主题:{channel};推送消息:{message};结果:{res}");
}
/// <summary>
/// 订阅消息
/// </summary>
/// <param name="channel"></param>
/// <param name="onMessageReceived"></param>
public void SubscribeToChannel(string channel, Action<string, string> onMessageReceived)
{
_subscriber.Subscribe(channel, (ch, message) =>
{
onMessageReceived(ch, message);
_logger.LogInformation($"订阅主题:{channel};收到主题:{ch};推送的消息:{message}");
});
}
public void CleanExpiredMessages(string channel)
{
var redis = _subscriber.Multiplexer.GetDatabase();
redis.KeyDelete(channel);
}
public void SetValue(string key,string message)
{
IDatabase db = redis.GetDatabase(0);
TimeSpan expiry = TimeSpan.FromSeconds(10);
db.StringSet(key, message, expiry);
}
}
}