/// <summary> /// Starts listening for messages /// </summary> public void StartListening() { // Queue name var queueName = QueueHandler.GetType().FullName; // Creates the exchange and queue if (ExchangeInfo == null) { ExchangeInfo = RabbitHelper.CreateExchange(Configuration); // Coda ExchangeInfo.Channel.QueueDeclare(queue: queueName, durable: true, exclusive: false, autoDelete: false); // Routing key var routingKey = typeof(TMessage).FullName; // Binding ExchangeInfo.Channel.QueueBind(queueName, ExchangeInfo.ExchangeName, routingKey); } ; // Create a consumer Consumer = new EventingBasicConsumer(ExchangeInfo.Channel); Consumer.Received += (model, arg) => { var json = Encoding.UTF8.GetString(arg.Body); var obj = JsonConvert.DeserializeObject <TMessage>(json); QueueHandler.HandleMessage(obj); ExchangeInfo.Channel.BasicAck(deliveryTag: arg.DeliveryTag, multiple: false); }; ExchangeInfo.Channel.BasicConsume(queueName, autoAck: false, consumer: Consumer); }
/// <summary> /// Send a message to the queue /// </summary> /// <param name="message">Message to send</param> /// <param name="ttl">Time To Live (0 = forever)</param> public void Send(TMessage message, long ttl = 0) { if (ExchangeInfo == null) { ExchangeInfo = RabbitHelper.CreateExchange(Configuration); } var routingKey = typeof(TMessage).FullName; IBasicProperties props = ExchangeInfo.Channel.CreateBasicProperties(); props.ContentEncoding = "UTF-8"; props.ContentType = "application/json"; props.DeliveryMode = 2; if (ttl > 0) { props.Expiration = ttl.ToString(); } ExchangeInfo.Channel.BasicPublish(exchange: ExchangeInfo.ExchangeName, routingKey: routingKey, body: Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message)), basicProperties: props); }