using Microsoft.Extensions.Logging; using SlnMesnac.Config; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Text; #region << 版 本 注 释 >> /*-------------------------------------------------------------------- * 版权所有 (c) 2024 WenJY 保留所有权利。 * CLR版本:4.0.30319.42000 * 机器名称:LAPTOP-E0N2L34V * 命名空间:SlnMesnac.Redis * 唯一标识:00418016-53c9-4f87-a13f-daa19d656bba * * 创建者:WenJY * 电子邮箱:wenjy@mesnac.com * 创建时间:2024-04-12 15:15:25 * 版本:V1.0.0 * 描述: * *-------------------------------------------------------------------- * 修改人: * 时间: * 修改说明: * * 版本:V1.0.0 *--------------------------------------------------------------------*/ #endregion << 版 本 注 释 >> namespace SlnMesnac.Redis { public class RedisHandler { private ILogger _logger; private readonly AppConfig _appConfig; private readonly ISubscriber _subscriber; private readonly ConnectionMultiplexer redis; public RedisHandler(AppConfig appConfig, ILogger logger) { _appConfig = appConfig; redis = ConnectionMultiplexer.Connect(_appConfig.redisConfig); _subscriber = redis.GetSubscriber(); _logger = logger; } /// /// 推送消息 /// /// /// public void PublishMessage(string channel, string message) { long res = _subscriber.Publish(channel, message); _logger.LogInformation($"向主题:{channel};推送消息:{message};结果:{res}"); } /// /// 订阅消息 /// /// /// public void SubscribeToChannel(string channel, Action 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); } } }