Guest User

Untitled

a guest
Oct 16th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.74 KB | None | 0 0
  1. public class RabbitListener<T>
  2. {
  3. private IModel model;
  4. private IConnection connection;
  5. private string queueName;
  6. Action<T> todo;
  7.  
  8. public RabbitListener(IModel model, IConnection connection, string queueName)
  9. {
  10. this.model = model;
  11. this.connection = connection;
  12. this.queueName = queueName;
  13. }
  14.  
  15. public void Subscribe(Factory<T> messageFactory, Action<T> action)
  16. {
  17. messageFactory.Binder.Bind(model,queueName);
  18. todo = action;
  19. }
  20.  
  21. public void Start(T message)
  22. {
  23. this.todo(message);
  24. }
  25. }
  26.  
  27. class Program
  28. {
  29. public static void DoSomethingWithMessage(StatusMessage s) { Console.WriteLine(s.Status); }
  30.  
  31. static void Main(string[] args)
  32. {
  33. string queueName = "Rite.EDI.RTI.Queue";
  34. IConnection connection = GetConnection();
  35. IModel model = connection.CreateModel();
  36.  
  37. //listeners
  38. RabbitListener<StatusMessage> statusListener =
  39. new RabbitListener<StatusMessage>(model, connection, queueName);
  40. Factory<StatusMessage> factory =
  41. new Factory<StatusMessage>(new StatusMessage(){System ="rite", Status = "X"});
  42.  
  43. statusListener.Subscribe(factory, p => DoSomethingWithMessage(p));
  44.  
  45. var subscription = new Subscription(model, queueName, true);
  46.  
  47. while (true)
  48. {
  49. var basicDeliveryEventArgs = subscription.Next();
  50.  
  51. if (basicDeliveryEventArgs == null)
  52. throw new OperationInterruptedException(
  53. new ShutdownEventArgs(ShutdownInitiator.Application, 0, "connection lost"));
  54. else
  55. {
  56. RabbitMessage message = new RabbitMessage(){
  57. body = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body),
  58. routingKey = basicDeliveryEventArgs.RoutingKey} ;
  59. foreach(var key in factory.Keys)
  60. if(key == message.routingKey)
  61. statusListener.Start(factory.BuildStatusMessage(message));
  62. }
  63. }
  64. }
  65.  
  66. static public IConnection GetConnection()
  67. {
  68. IConnection connection = new ConnectionFactory
  69. {
  70. HostName = (string)ConfigurationManager.AppSettings["mqHost"],
  71. UserName = (string)ConfigurationManager.AppSettings["mqUser"],
  72. Password = (string)ConfigurationManager.AppSettings["mqPass"]
  73. }
  74. .CreateConnection();
  75.  
  76. return connection;
  77. }
  78. }
Add Comment
Please, Sign In to add comment