StackExchange.Redis还支持通过pub / sub通道发送字节,这里我们使用protobuf-net将消息序列化为字节数组,然后再发送:
// 消息的定义(用Protobuf属性标记) [ProtoContract] public class ChatMessage { [ProtoMember(1)] public Guid Id { get; set; } [ProtoMember(2)] public string User { get; set; } [ProtoMember(3)] public string Text { get; set; } } // 抓取一个ISubscriber的实例 var subscriber = connection.GetSubscriber(); var message = new ChatMessage { Id = Guid.NewGuid(), User = "User 1234", Text = "你好,世界!" }; using (var memoryStream = new MemoryStream()) { // 使用protobuf-net序列化ChatMessage Serializer.Serialize(memoryStream, message); // 将消息发布到“聊天”频道 subscriber.Publish("chat", memoryStream.ToArray()); }
订户再次需要在收到消息后反序列化消息:
// 抓取一个ISubscriber的实例 var subscriber = connection.GetSubscriber(); // 通过“聊天”频道订阅消息 subscriber.Subscribe("chat", (channel, bytes) => { using (var memoryStream = new MemoryStream(bytes)) { var message = Serializer.Deserialize<ChatMessage>(memoryStream); // 用消息做点什么 Console.WriteLine($"{message.User} said {message.Text}"); } });