Created
July 19, 2020 16:09
-
-
Save alexandrebl/d3e6d01cd06b87b6314eceff8ca4da25 to your computer and use it in GitHub Desktop.
RabbitMQ Publish Confirmation and Return Message CSharp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using RabbitMQ.Client; | |
| using System; | |
| using System.Text; | |
| using System.Threading; | |
| namespace Publisher | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var factory = new ConnectionFactory() { HostName = "localhost" }; | |
| using (var connection = factory.CreateConnection()) | |
| using (var channel = connection.CreateModel()) | |
| { | |
| try | |
| { | |
| channel.ConfirmSelect(); | |
| channel.BasicAcks += Channel_BasicAcks; | |
| channel.BasicNacks += Channel_BasicNacks; | |
| channel.BasicReturn += Channel_BasicReturn; | |
| channel.QueueDeclare(queue: "order", | |
| durable: false, | |
| exclusive: false, | |
| autoDelete: false, | |
| arguments: null); | |
| string message = $"{DateTime.UtcNow:o} -> Hello World!"; | |
| var body = Encoding.UTF8.GetBytes(message); | |
| channel.BasicPublish(exchange: "", | |
| routingKey: "orderssssss", | |
| basicProperties: null, | |
| body: body, | |
| mandatory: true); | |
| channel.WaitForConfirms(new TimeSpan(0, 0, 5)); | |
| Console.WriteLine(" [x] Sent {0}", message); | |
| }catch(Exception ex) | |
| { | |
| //Tratar o erro | |
| //Verificar se o canal está aberto ou não | |
| //Abrir o canal e reconectar o consumidor | |
| } | |
| } | |
| Console.WriteLine(" Press [enter] to exit."); | |
| Console.ReadLine(); | |
| } | |
| private static void Channel_BasicAcks(object sender, RabbitMQ.Client.Events.BasicAckEventArgs e) | |
| { | |
| Console.WriteLine($"{DateTime.UtcNow:o} -> Basic Ack"); | |
| } | |
| private static void Channel_BasicNacks(object sender, RabbitMQ.Client.Events.BasicNackEventArgs e) | |
| { | |
| Console.WriteLine($"{DateTime.UtcNow:o} -> Basic Nack"); | |
| } | |
| private static void Channel_BasicReturn(object sender, RabbitMQ.Client.Events.BasicReturnEventArgs e) | |
| { | |
| var message = Encoding.UTF8.GetString(e.Body.ToArray()); | |
| Console.WriteLine($"{DateTime.UtcNow:o} -> Basic Return -> Original message -> {message}"); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment