Guest User

Untitled

a guest
Nov 11th, 2018
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.65 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using Microsoft.Extensions.Configuration;
  5. using Microsoft.Extensions.Options;
  6. using RabbitMQ.Client;
  7. using RabbitMQ.Client.Events;
  8.  
  9. namespace ProcessadorMensagens
  10. {
  11. class Program
  12. {
  13. private static IConfiguration _configuration;
  14.  
  15. static void Main(string[] args)
  16. {
  17. var builder = new ConfigurationBuilder()
  18. .SetBasePath(Directory.GetCurrentDirectory())
  19. .AddJsonFile($"appsettings.json");
  20. _configuration = builder.Build();
  21.  
  22. // Para este exemplo foi criado um container Docker baseado
  23. // em uma imagem do RabbitMQ. Segue o comando para geração
  24. // desta estrutura:
  25. // docker run -d --hostname rabbit-local --name testes-rabbitmq -p 6672:5672 -p 15672:15672 -e RABBITMQ_DEFAULT_USER=testes -e RABBITMQ_DEFAULT_PASS=Testes2018! rabbitmq:3-management-alpine
  26. var rabbitMQConfigurations = new RabbitMQConfigurations();
  27. new ConfigureFromConfigurationOptions<RabbitMQConfigurations>(
  28. _configuration.GetSection("RabbitMQConfigurations"))
  29. .Configure(rabbitMQConfigurations);
  30.  
  31. var factory = new ConnectionFactory()
  32. {
  33. HostName = rabbitMQConfigurations.HostName,
  34. Port = rabbitMQConfigurations.Port,
  35. UserName = rabbitMQConfigurations.UserName,
  36. Password = rabbitMQConfigurations.Password
  37. };
  38.  
  39. using (var connection = factory.CreateConnection())
  40. using (var channel = connection.CreateModel())
  41. {
  42. channel.QueueDeclare(queue: "TestesASPNETCore",
  43. durable: false,
  44. exclusive: false,
  45. autoDelete: false,
  46. arguments: null);
  47.  
  48. var consumer = new EventingBasicConsumer(channel);
  49. consumer.Received += Consumer_Received;
  50. channel.BasicConsume(queue: "TestesASPNETCore",
  51. autoAck: true,
  52. consumer: consumer);
  53.  
  54. Console.WriteLine("Aguardando mensagens para processamento");
  55. Console.WriteLine("Pressione uma tecla para encerrar...");
  56. Console.ReadKey();
  57. }
  58. }
  59.  
  60.  
  61. private static void Consumer_Received(
  62. object sender, BasicDeliverEventArgs e)
  63. {
  64. var message = Encoding.UTF8.GetString(e.Body);
  65. Console.WriteLine(Environment.NewLine +
  66. "[Nova mensagem recebida] " + message);
  67. }
  68. }
  69. }
Add Comment
Please, Sign In to add comment