/// <summary>
        /// Register to receive Messages pertaining to a Topic
        /// </summary>
        /// <param name="Topic">The topic to subscribe for</param>
        /// <param name="consumer">The object that is subscribing for this Topic</param>
        public void RegisterTopic(string Topic, IMessageDestination consumer)
        {
            mLogger.Debug(string.Format("Consumer {0} registered for topic {1}", consumer.GetType(), Topic));

            if (ConsumerTopicDictionary.ContainsKey(consumer))
            {
                ConsumerTopicDictionary[consumer].Add(Topic);
            }
            else
            {
                List <string> list = new List <string>();
                list.Add(Topic);
                ConsumerTopicDictionary.TryAdd(consumer, list);
            }

            if (TopicConsumerDictionary.ContainsKey(Topic))
            {
                TopicConsumerDictionary[Topic].Add(consumer);
            }
            else
            {
                List <IMessageDestination> list = new List <IMessageDestination>();
                list.Add(consumer);
                TopicConsumerDictionary.TryAdd(Topic, list);
            }
        }
Exemple #2
0
 public IncomingMessage(object content, String correlationId, 
     String sender, IMessageDestination topic,
     IMessageDestination replyTo) : base(content, correlationId)
 {
     _sender = sender;
     _topic = topic;
     _replyTo = replyTo;
     _timeOfArrival = DateTime.UtcNow;
 }
        private MessagePipeline ConnectSourceDestination(IMessageSource source, IMessageDestination target)
        {
            var sourceWriter     = source as IMessageWriter;
            var targetReader     = target as IMessageReader;
            var pipelineElements = new List <IMessageProcessor>();

            if (sourceWriter != null && targetReader != null)
            {
                pipelineElements.Insert(0, target);
                if (sourceWriter.OutMessageDescriptorType() == typeof(RawMessageDescriptor))
                {
                    if (targetReader.InMessageDescriptorType() == typeof(RawMessageDescriptor))
                    {
                        // nothing to do here, join will go ok
                    }
                    else if (targetReader.InMessageDescriptorType() == typeof(MsgDescriptor))
                    {
                        pipelineElements.Insert(0,
                                                new RawToMsgProcessor()
                        {
                            Name       = source.Name,
                            NextReader = (IMessageReader <MsgDescriptor>)target
                        });
                    }
                    else
                    {
                        throw new Exception("Unsupported connection types, need " +
                                            targetReader.InMessageDescriptorType() + " writer.");
                    }
                }
                else if (sourceWriter.OutMessageDescriptorType() == typeof(MsgDescriptor))
                {
                    if (targetReader.InMessageDescriptorType() == typeof(MsgDescriptor))
                    {
                        // nothing to do here, join will go ok
                    }
                    else
                    {
                        throw new Exception("Unsupported connection types, need " +
                                            targetReader.InMessageDescriptorType() + " writer.");
                    }
                }
                else
                {
                    throw new Exception("Unsupported connection types, need " + sourceWriter.OutMessageDescriptorType() +
                                        " reader.");
                }
                pipelineElements.Insert(0, source);
            }
            return(new MessagePipeline(pipelineElements));
        }
        /// <summary>
        /// Send a message to one subscriber. The recepient will handle it immediately
        /// If there are multiple subscribers, the first will handle it, and move to the end of the line (like a queue)
        /// </summary>
        /// <param name="Topic">The topic to associate with this message</param>
        /// <param name="message">The message to send</param>
        /// <param name="ReturnValue">An object to return</param>
        /// <returns>Whether or not the message successfully went through</returns>
        public bool SendMessageImmediate(string Topic, IMessage message, ref object ReturnValue)
        {
            if (TopicConsumerDictionary.ContainsKey(Topic))
            {
                IMessageDestination dest = TopicConsumerDictionary[Topic][0];
                TopicConsumerDictionary[Topic].Remove(dest);
                TopicConsumerDictionary[Topic].Add(dest);

                return(dest.HandleMessage(Topic, message, ref ReturnValue));
            }
            else
            {
                return(false);
            }
        }
        public void Send(IMessageDestination destination, IMessageWrapper message,
            IMessageDestination responseDestination = null)
        {
            Logger.Debug(this, String.Format("{0}: Just sending message to {1} with correlation id {2}", this.ConnectionId, destination.Address,
                message.CorrelationId));
            IBasicProperties basicProperties = _session.Use.CreateBasicProperties();
            basicProperties.AppId = this.ConnectionId;
            basicProperties.CorrelationId = message.CorrelationId;
            if (responseDestination != null)
                basicProperties.ReplyTo = responseDestination.Address;
            _session.Use.BasicPublish(EXCHANGE_NAME, destination.Address,
                basicProperties, Formatter.Serialize(message.Content.ToString()));
            Logger.Debug(this, String.Format("{0}: Just sent message to {1} with correlation id {2}", this.ConnectionId, destination.Address,
                message.CorrelationId));

        }
        protected void SubscribeCore(IMessageDestination messageDestination, Action<IIncomingMessage> incomingMessageHandler)
        {
            Logger.Debug(this, String.Format("{0}: Subscribing to topic {1}", this.ConnectionId, messageDestination.Address));
            String topic = messageDestination.Address;
            if (!_incomingMessageManager.KnownMessageProcessors.Keys.Contains(messageDestination))
            {
                _session.Use.QueueDeclare(topic, false, false, false, null);
                _session.Use.QueueBind(topic, EXCHANGE_NAME, topic);
                
            }


            var messageProcessor = new DefaultBroadcastProcessor();
            _incomingMessageManager.KnownMessageProcessors.GetOrAdd(
                 messageDestination, messageProcessor);
            messageProcessor.OnMessageReceived += incomingMessageHandler;
            
            var consumer = new RabbitMessageConsumer(
                evt =>
                    {
                        try
                        {
                            Logger.Debug(this, "Received new message...");
                            string sender = evt.BasicProperties.AppId;
                            string routingKey = evt.RoutingKey;
                            string correlationId = evt.BasicProperties.CorrelationId;
                            string responseTopic = evt.BasicProperties.ReplyTo;
                            //IMessage
                            var content = _config.Formatter.Deserialize(evt.Body);
                            var incomingMessage = new IncomingMessage(content, correlationId,
                                sender,
                                new MessageDestination(routingKey),
                                new MessageDestination(responseTopic));
                            _incomingMessageManager.IncomingMessageQueue.Add(incomingMessage);
                        }
                        finally
                        {
                            //Take it off the message queue
                            _session.Use.BasicAck(evt.DeliveryTag, false);                            
                        }
                        
                    });

            var consumerTag = _session.Use.BasicConsume(topic, false, consumer);
            _consumerDict.Add(messageDestination, consumerTag);
            Logger.Debug(this, String.Format("{0}: Subscribed to topic {1}", this.ConnectionId, messageDestination.Address));
        }
 public void Unsubscribe(IMessageDestination topicOrQueue)
 {
     bool unsubscribed = false;
     while (!unsubscribed)
     {
         _receiverChannelPool.UsingObjectFromPool(
             rc =>
                 {
                     if (rc.Subscriptions
                           .Any(msgDest => msgDest.Address.Equals(topicOrQueue.Address)))
                     {
                         rc.Unsubscribe(topicOrQueue);
                         unsubscribed = true;
                     }
                 });
     }
 }
 public void Send(IMessageDestination topicOrQueue, IMessageWrapper message,
                  Action<IIncomingMessage> responseHandler = null)
 {
     _senderChannelPool.UsingObjectFromPool(
     senderChannel =>
     {
         if (responseHandler != null)
         {
             _receiverChannelPool.ResponseProcessor.
                 AddSpecificResponseHandler(message.CorrelationId, responseHandler);
             senderChannel.Send(topicOrQueue, message, 
                 _receiverChannelPool.UniqueResponseDestination);
         }
         else
         {
             senderChannel.Send(topicOrQueue, message);
         }
     });
 }
        /// <summary>
        /// Get all messages for subscribed topics
        /// </summary>
        /// <returns>A dictionary of topics and list of messages associated with the topic</returns>
        public Dictionary <string, List <IMessage> > GetMessages(IMessageDestination consumer)
        {
            if (!ConsumerTopicDictionary.ContainsKey(consumer))
            {
                return(new Dictionary <string, List <IMessage> >());
            }
            List <string> subscribedTopics = ConsumerTopicDictionary[consumer];
            Dictionary <string, List <IMessage> > returnDict = new Dictionary <string, List <IMessage> >();

            foreach (string Topic in subscribedTopics)
            {
                if (mCurrentFrameMessages.ContainsKey(Topic))
                {
                    returnDict.Add(Topic, mCurrentFrameMessages[Topic]);
                }
            }

            return(returnDict);
        }
        /// <summary>
        /// Deregister a consumer from a topic
        /// </summary>
        /// <param name="Topic">The topic to degister from</param>
        /// <param name="consumer">The consumer to deregister</param>
        public void DeregisterTopic(string Topic, IMessageDestination consumer)
        {
            mLogger.Debug(string.Format("Consumer {0} deregistered for topic {1}", consumer.GetType(), Topic));

            if (ConsumerTopicDictionary.ContainsKey(consumer))
            {
                ConsumerTopicDictionary[consumer].Remove(Topic);
                if (ConsumerTopicDictionary[consumer].Count == 0) // There are no more topics for this consumer
                {
                    List <string> outList = new List <string>();
                    ConsumerTopicDictionary.TryRemove(consumer, out outList);
                }
            }

            if (TopicConsumerDictionary.ContainsKey(Topic))
            {
                TopicConsumerDictionary[Topic].Remove(consumer);
                if (TopicConsumerDictionary[Topic].Count == 0) // There are no more consumers for this topic
                {
                    List <IMessageDestination> outList = new List <IMessageDestination>();
                    TopicConsumerDictionary.TryRemove(Topic, out outList);
                }
            }
        }
 public void Unsubscribe(IMessageDestination topicOrQueue)
 {
     _threadSafeExecutor.Do(() => UnsubscribeCore(topicOrQueue));
 }
 public void Subscribe(IMessageDestination topicOrQueue, Action<IIncomingMessage> incomingMessageHandler)
 {
     _threadSafeExecutor.Do(() => SubscribeCore(topicOrQueue, incomingMessageHandler));
 }
 protected void UnsubscribeCore(IMessageDestination messageDestination)
 {
     if (_consumerDict.ContainsKey(messageDestination))
     {
         var consumerTag = _consumerDict[messageDestination];
         if (!String.IsNullOrEmpty(consumerTag))
             _session.Use.BasicCancel(consumerTag);
         _consumerDict.Remove(messageDestination);
     }
 }
 public void Subscribe(IMessageDestination topicOrQueue, Action<IIncomingMessage> incomingMessageHandler)
 {
     _receiverChannelPool.UsingObjectFromPool(c => c.Subscribe(
         topicOrQueue, incomingMessageHandler));
 }
 public Task<IIncomingMessage> SendAsync(IMessageDestination topicOrQueue, 
     IMessageWrapper message)
 {
     throw new NotImplementedException();
 }