c# - RabbitMQ Pub/Sub - Subscriber is not able to receive message -
i using sample code implement publish/subscribe using "fanout" exchange type. in below code subscriber not displaying 'hello word' message published.
publisher.cs
var factory = new connectionfactory() { hostname = "localhost" }; using (var connection = factory.createconnection()) using (var channel = connection.createmodel()) { channel.exchangedeclare(exchange: "logs", type: "fanout"); var message = getmessage(args); var body = encoding.utf8.getbytes(message); channel.basicpublish(exchange: "logs", routingkey: "", basicproperties: null, body: body); console.writeline(" [x] sent {0}", message); } console.writeline(" press [enter] exit."); console.readline(); } private static string getmessage(string[] args) { return ((args.length > 0) ? string.join(" ", args) : "info: hello world!"); }
subscriber.cs
var factory = new connectionfactory() { hostname = "localhost" }; using (var connection = factory.createconnection()) using (var channel = connection.createmodel()) { channel.exchangedeclare(exchange: "logs", type: "fanout"); var queuename = channel.queuedeclare().queuename; channel.queuebind(queue: queuename, exchange: "logs", routingkey: ""); console.writeline(" [*] waiting logs."); var consumer = new eventingbasicconsumer(channel); consumer.received += (model, ea) => { var body = ea.body; var message = encoding.utf8.getstring(body); console.writeline(" [x] {0}", message); }; channel.basicconsume(queue: queuename, noack: true, consumer: consumer); console.writeline(" press [enter] exit."); console.readline(); }
code ref: https://www.rabbitmq.com/tutorials/tutorial-three-dotnet.html
as figured out works, need start subscriber first. why? answer on link provided. i'll quote 1 part here:
but that's not case our logger. want hear log messages, not subset of them. we're interested in currently flowing messages not in old ones. solve need 2 things.
firstly, whenever connect rabbit we need fresh, empty queue. create queue random name, or, better - let server choose random queue name us.
secondly, once disconnect consumer queue should automatically deleted.
this means queue created when start subscriber, , @ point, exchange has queue put message in. since fist start publisher, there no queue message end in.
Comments
Post a Comment