89 lines
2.8 KiB
C#
89 lines
2.8 KiB
C#
using MessagePack;
|
||
using StackExchange.Redis;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Text.Json;
|
||
using System.Threading.Channels;
|
||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||
|
||
class Subscriber
|
||
{
|
||
static void Main(string[] args)
|
||
{
|
||
Console.WriteLine("请输入redis的ip地址:");
|
||
Console.WriteLine("直接回车默认使用127.0.0.1");
|
||
|
||
string ip = Console.ReadLine();
|
||
if (string.IsNullOrWhiteSpace(ip))
|
||
{
|
||
ip = "192.168.81.22";
|
||
}
|
||
var connectStr = $"{ip}:36379,defaultDatabase=0,password=yunda123";
|
||
var configurationOptions = new ConfigurationOptions
|
||
{
|
||
EndPoints = { $"{ip}:36379" },
|
||
ConnectTimeout = 20000,
|
||
AsyncTimeout = 20000,
|
||
SyncTimeout = 20000,
|
||
DefaultDatabase = 0,
|
||
Password = "yunda123",
|
||
};
|
||
|
||
var conmper = ConnectionMultiplexer.Connect(configurationOptions);
|
||
var confOption = ConfigurationOptions.Parse(connectStr);
|
||
var server = conmper.GetServer(confOption.EndPoints[0]);
|
||
var sub = conmper.GetSubscriber();
|
||
Console.WriteLine("请输入redis的channel地址:");
|
||
string channel = Console.ReadLine();
|
||
|
||
long receivedCount = 0;
|
||
DateTime startTime = DateTime.Now;
|
||
|
||
sub.Subscribe(channel, (channel, message) =>
|
||
{
|
||
receivedCount++;
|
||
|
||
// 解析 JSON 消息
|
||
var entity = MessagePackSerializer.Deserialize<Dictionary<string, object>>(message, MessagePack.Resolvers.ContractlessStandardResolver.Options);
|
||
ProcessDictionary(entity);
|
||
|
||
|
||
});
|
||
|
||
Console.WriteLine("按 Enter 键退出程序...");
|
||
Console.ReadLine();
|
||
|
||
conmper.Dispose();
|
||
}
|
||
static void ProcessDictionary(Dictionary<string, object> dictionary)
|
||
{
|
||
foreach (var kvp in dictionary)
|
||
{
|
||
Console.Write($"{kvp.Key}: ");
|
||
if (kvp.Value is byte[] nestedMessagePack)
|
||
{
|
||
try
|
||
{
|
||
// 进一步解析嵌套的 MessagePack 数据
|
||
var nestedDict = MessagePackSerializer.Deserialize<Dictionary<string, object>>(nestedMessagePack, MessagePack.Resolvers.ContractlessStandardResolver.Options);
|
||
Console.WriteLine();
|
||
ProcessDictionary(nestedDict); // 递归解析
|
||
}
|
||
catch
|
||
{
|
||
Console.WriteLine("(嵌套内容无法解析)");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine(kvp.Value);
|
||
}
|
||
}
|
||
}
|
||
public class Message
|
||
{
|
||
public string name { get; set; }
|
||
public int index { get; set; }
|
||
}
|
||
}
|