我有一台带redis的远程计算机。我使用简单的c#客户端从中侦听事件:
public partial class VerificationResultsService : ServiceBase
{
private const string ChatChannel = "__keyevent@0__:hset";
public void Start()
{
using (ConnectionMultiplexer muxer =
ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["ModuleControlRedisConnection"]))
{
muxer.GetServer(muxer.GetEndPoints().Single())
.ConfigSet("notify-keyspace-events", "KEA");
muxer.GetSubscriber().Subscribe(ChatChannel,
(channel, message) => MessageAction(message, channel, muxer));
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
}
private static void MessageAction(RedisValue message, RedisChannel channel, ConnectionMultiplexer muxer)
{
Console.WriteLine($"received {message} on {channel}");
}
}
我得到这样的输出:
输出中类似guid的部分(消息)是redis中的键。如何获取与此键关联的值?keytype方法为此键返回“hash”。
我使用.net core和microsoft.extensions.caching.stackexchangeredis 3.1.2实现了我的目标,但我需要.net framework解决方案,因为此库不适用于.net framework:
class Program
{
private const string ChatChannel = "__keyevent@0__:hset";
static void Main()
{
var serviceProvider = new ServiceCollection()
.AddStackExchangeRedisCache(options =>
{
options.ConfigurationOptions = new ConfigurationOptions()
{
Password = "",
EndPoints = { $"" },
};
})
.BuildServiceProvider();
var bar = serviceProvider.GetService<IDistributedCache>();
using var muxer = ConnectionMultiplexer.Connect("172.20.62.5:6379,allowAdmin=true");
muxer.GetServer(muxer.GetEndPoints().Single())
.ConfigSet("notify-keyspace-events", "KEA");
muxer.GetSubscriber().Subscribe(ChatChannel,
(channel, message) => MessageAction(message, channel, muxer, bar));
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
private static async void MessageAction(RedisValue message, RedisChannel channel, ConnectionMultiplexer muxer, IDistributedCache bar)
{
MemoryStream resultMessage = new MemoryStream();
var info = bar.Get(message.ToString());
if (info != default(byte[]) && info.Length != 0)
await Decompess(info, resultMessage);
var value1 = Encoding.UTF8.GetString(resultMessage.ToArray());
Console.WriteLine(value1);
Console.WriteLine($"received {message} on {channel}");
}
private static async Task Decompess(byte[] loadedData, MemoryStream result)
{
await using var input = new MemoryStream(loadedData);
await using var zipStream = new GZipStream(input, CompressionMode.Decompress);
await zipStream.CopyToAsync(result);
}
}
暂无答案!
目前还没有任何答案,快来回答吧!