Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RabbitListener<T>
- {
- private IModel model;
- private IConnection connection;
- private string queueName;
- Action<T> todo;
- public RabbitListener(IModel model, IConnection connection, string queueName)
- {
- this.model = model;
- this.connection = connection;
- this.queueName = queueName;
- }
- public void Subscribe(Factory<T> messageFactory, Action<T> action)
- {
- messageFactory.Binder.Bind(model,queueName);
- todo = action;
- }
- public void Start(T message)
- {
- this.todo(message);
- }
- }
- class Program
- {
- public static void DoSomethingWithMessage(StatusMessage s) { Console.WriteLine(s.Status); }
- static void Main(string[] args)
- {
- string queueName = "Rite.EDI.RTI.Queue";
- IConnection connection = GetConnection();
- IModel model = connection.CreateModel();
- //listeners
- RabbitListener<StatusMessage> statusListener =
- new RabbitListener<StatusMessage>(model, connection, queueName);
- Factory<StatusMessage> factory =
- new Factory<StatusMessage>(new StatusMessage(){System ="rite", Status = "X"});
- statusListener.Subscribe(factory, p => DoSomethingWithMessage(p));
- var subscription = new Subscription(model, queueName, true);
- while (true)
- {
- var basicDeliveryEventArgs = subscription.Next();
- if (basicDeliveryEventArgs == null)
- throw new OperationInterruptedException(
- new ShutdownEventArgs(ShutdownInitiator.Application, 0, "connection lost"));
- else
- {
- RabbitMessage message = new RabbitMessage(){
- body = Encoding.UTF8.GetString(basicDeliveryEventArgs.Body),
- routingKey = basicDeliveryEventArgs.RoutingKey} ;
- foreach(var key in factory.Keys)
- if(key == message.routingKey)
- statusListener.Start(factory.BuildStatusMessage(message));
- }
- }
- }
- static public IConnection GetConnection()
- {
- IConnection connection = new ConnectionFactory
- {
- HostName = (string)ConfigurationManager.AppSettings["mqHost"],
- UserName = (string)ConfigurationManager.AppSettings["mqUser"],
- Password = (string)ConfigurationManager.AppSettings["mqPass"]
- }
- .CreateConnection();
- return connection;
- }
- }
Add Comment
Please, Sign In to add comment