vitareinforce

worker

Sep 15th, 2022
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.79 KB | None | 0 0
  1. using RabbitMQ.Client;
  2. using RabbitMQ.Client.Events;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Text;
  6. using System.Threading;
  7.  
  8. namespace Worker
  9. {
  10. class RMQ
  11. {
  12. public ConnectionFactory connectionFactory;
  13. public IConnection connection;
  14. public IModel channel;
  15. private bool isReceiving = false;
  16. public void InitRMQConnection(string host = "rmq2.pptik.id", int port = 5672, string user = "TMDG2022", string pass = "TMDG2022", string vhost="/TMDG2022")
  17. {
  18. connectionFactory = new ConnectionFactory();
  19. connectionFactory.HostName = host;
  20. connectionFactory.Port = port;
  21. connectionFactory.UserName = user;
  22. connectionFactory.Password = pass;
  23. connectionFactory.VirtualHost = vhost;
  24. }
  25. public void CreateRMQConnection()
  26. {
  27. connection = connectionFactory.CreateConnection();
  28. Console.WriteLine("Koneksi " + (connection.IsOpen ? "Berhasil!" : "Gagal!"));
  29. }
  30. public void WaitingMessage(string queue_name)
  31. {
  32. using (channel = connection.CreateModel())
  33. {
  34. channel.QueueDeclare(queue: queue_name,
  35. durable: true,
  36. exclusive: false,
  37. autoDelete: false,
  38. arguments: null);
  39. var consumer = new EventingBasicConsumer(channel);
  40. consumer.Received += (model, ea) =>
  41. {
  42. var body = ea.Body.ToArray();
  43. var message = Encoding.UTF8.GetString(body);
  44. Console.WriteLine(" [x] Pesan diterima: {0}", message);
  45. int angka = Int32.Parse(message);
  46. CountDown(angka);
  47. };
  48. channel.BasicConsume(queue: queue_name,
  49. autoAck: true,
  50. consumer: consumer);
  51. Console.WriteLine(" Tekan [enter] untuk memutus koneksi.");
  52. Console.ReadLine();
  53. Disconnect();
  54. }
  55. }
  56.  
  57. public void CountDown(int start)
  58. {
  59. for (int i = start; i > 0; i--)
  60. {
  61. Console.Write(i + " ");
  62. Thread.Sleep(1000);
  63. }
  64. Console.WriteLine("Done Computing");
  65. }
  66.  
  67.  
  68. public void Disconnect()
  69. {
  70. isReceiving = false;
  71. channel.Close();
  72. channel = null;
  73. Console.WriteLine("Channel ditutup!");
  74. if (connection.IsOpen)
  75. {
  76. connection.Close();
  77. }
  78. Console.WriteLine("Koneksi diputus!");
  79. connection.Dispose();
  80. connection = null;
  81. }
  82. }
  83. }
  84.  
Add Comment
Please, Sign In to add comment