Recently, I started to use easynetq in my project. I got to know about the next api and looked at the examples on the internet. As a result, none of them worked successfully, and none of the simplest publishing and subscribing succeeded. I'm an example of someone else running directly. I shouldn't, but I've been analyzing it all the time. Finally, I find that the message is not serialized. This is one of them. Secondly, we should get up the receiving end of the message first, and then the publishing end of the message. At first it was simple:
static void Main() { using( var bus = RabbitHutch.CreateBus( "host=localhost" ) ) { bus.Subscribe<TextMessage>( "test", HandleTextMessage ); Console.WriteLine( "Listening for messages. Hit <return> to quit." ); Console.ReadLine(); } } static void HandleTextMessage( TextMessage textMessage ) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine( $"Got message {textMessage.Text}" ); }
private static void Main() { using (var bus = RabbitHutch.CreateBus("host=localhost")) { var input = ""; Console.WriteLine("Enter a message. 'Quit' to quit."); while ((input = Console.ReadLine())?.ToUpper() != "QUIT") { bus.Publish(new TextMessage { Text = input }); } } }
public class TextMessage { public string Text { get; set; } }
As a result, black window or black window, why is there no output of message subscription? It's because our messages are not serialized. Increase on the publisher side:
bus.Publish<string>(JsonConvert.SerializeObject(new TextMessage{ Text = "Hello World" }));
Add:
var myMessage = (TextMessage)JsonConvert.DeserializeObject<TextMessage>(obj);
That's all right.
In fact, we can use the message class in the advanced API to wrap our messages, so that we don't need to serialize the messages at the publisher, but we still need to deserialize the messages at the receiver. Specifically, please refer to:
EasyNetQ - Advanced API