Looking for stackexchange.redis Answers? Try Ask4KnowledgeBase
Looking for stackexchange.redis Keywords? Try Ask4Keywords

StackExchange.Redis Komplexe Daten (Protobuf)


Beispiel

StackExchange.Redis unterstützt auch das Senden von Bytes über den Pub / Sub-Kanal. Hier verwenden wir protobuf-net, um unsere Nachricht vor dem Senden in ein Byte-Array zu serialisieren:

// definition of a message (marked up with Protobuf attributes)
[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; }
}

// grab an instance of an ISubscriber
var subscriber = connection.GetSubscriber();

var message = new ChatMessage
{
    Id = Guid.NewGuid(), 
    User = "User 1234", 
    Text = "Hello World!"
};

using (var memoryStream = new MemoryStream())
{
    // serialize a ChatMessage using protobuf-net
    Serializer.Serialize(memoryStream, message);

    // publish the message to the 'chat' channel
    subscriber.Publish("chat", memoryStream.ToArray());
}

Wieder muss der Teilnehmer die Nachricht nach Erhalt deserialisieren:

// grab an instance of an ISubscriber
var subscriber = connection.GetSubscriber();

// subscribe to messages over the 'chat' channel
subscriber.Subscribe("chat", (channel, bytes) => {
    using (var memoryStream = new MemoryStream(bytes))
    {
        var message = Serializer.Deserialize<ChatMessage>(memoryStream);

        // do something with the message
        Console.WriteLine($"{message.User} said {message.Text}");
    }
});