Example #1
0
        public void TransMedPublishesEvent()
        {
            //SystemX lytter
            _advancedBus.Consume(_systemXQueue,
                                 (IMessage <PatientHaveReceivedTreatmentAndCanBeInvoicedA97Event> msg, MessageReceivedInfo info) =>
            {
                Console.WriteLine($"SystemX mottok melding med routingkey {info.RoutingKey}: {JsonConvert.SerializeObject(msg.Body)}");
                _waitForMessage.Set();
            });

            //TransMed publiserer event
            var eventToPublish =
                new Message <PatientHaveReceivedTreatmentAndCanBeInvoicedA97Event>(new PatientHaveReceivedTreatmentAndCanBeInvoicedA97Event
            {
                NIN = "12345678901",
                TreatmentDescription = "Stivkrampevaksine",
                UserId = "les-123"
            });

            //sett AMQP properties (correlationid settes av easynetq, trenger ikke reply-to siden vi ikke skal ha svar)
            eventToPublish.Properties.Expiration =
                TimeSpan.FromDays(2).TotalMilliseconds.ToString(CultureInfo.InvariantCulture); //ttl
            eventToPublish.Properties.AppId = "TransMed";                                      //tilsvarer sanns. "sender"

            //publish
            _advancedBus.Publish(_systemXExchange, $"event.{nameof(PatientHaveReceivedTreatmentAndCanBeInvoicedA97Event)}", true, eventToPublish);

            _waitForMessage.WaitOne(3000);
        }
        public void FuturePublish <T>(DateTime futurePublishDate, T message, string cancellationKey = null) where T : class
        {
            Preconditions.CheckNotNull(message, "message");
            var scheduleMeType      = typeof(ScheduleMe);
            var scheduleMeExchange  = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, scheduleMeType, ExchangeType.Topic);
            var baseMessageType     = typeof(T);
            var concreteMessageType = message.GetType();
            var serializedMessage   = messageSerializationStrategy.SerializeMessage(new Message <T>(message)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(concreteMessageType)
                }
            });
            var scheduleMe = new ScheduleMe
            {
                WakeTime          = futurePublishDate,
                CancellationKey   = cancellationKey,
                InnerMessage      = serializedMessage.Body,
                MessageProperties = serializedMessage.Properties,
                BindingKey        = typeNameSerializer.Serialize(typeof(T)),
                ExchangeType      = ExchangeType.Topic,
                Exchange          = conventions.ExchangeNamingConvention(baseMessageType),
                RoutingKey        = "#"
            };
            var easyNetQMessage = new Message <ScheduleMe>(scheduleMe)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(scheduleMeType)
                }
            };

            advancedBus.Publish(scheduleMeExchange, conventions.TopicNamingConvention(scheduleMeType), false, easyNetQMessage);
        }
Example #3
0
        public void PublishToAnExchange()
        {
            var exchange = new Exchange("my_exchange");

            var body = Encoding.UTF8.GetBytes("Hello World!");

            advancedBus.Publish(exchange, "routing_key", false, false, new MessageProperties(), body);

            Thread.Sleep(500);
        }
Example #4
0
        private void RequestPublish <TRequest>(TRequest request, string returnQueueName) where TRequest : class
        {
            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));
            var exchange   = advancedBus.ExchangeDeclare(conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);

            var requestMessage = new Message <TRequest>(request);

            requestMessage.Properties.ReplyTo = returnQueueName;

            advancedBus.Publish(exchange, routingKey, false, false, requestMessage);
        }
Example #5
0
        private void RequestPublish <TRequest>(TRequest request, string returnQueueName, Guid correlationId) where TRequest : class
        {
            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));
            var exchange   = publishExchangeDeclareStrategy.DeclareExchange(
                advancedBus, conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);

            var requestMessage = new Message <TRequest>(request);

            requestMessage.Properties.ReplyTo       = returnQueueName;
            requestMessage.Properties.CorrelationId = correlationId.ToString();

            advancedBus.Publish(exchange, routingKey, false, false, requestMessage);
        }
        /// <summary>
        /// Publishes Admin Level request for Order Executions
        /// </summary>
        public void PublishOrderAdminMessage(string response)
        {
            try
            {
                // Message to be published
                IMessage <string> responseMessage = new Message <string>(response);

                _easyNetQBus.Publish(_easyNetQExchange, _adminQueueRoutingKey, true, false, responseMessage);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "PublishOrderAdminMessage");
            }
        }
Example #7
0
        protected virtual void RequestPublish <TRequest>(TRequest request, string routingKey, string returnQueueName, Guid correlationId)
            where TRequest : class
        {
            var exchange       = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);
            var requestType    = typeof(TRequest);
            var requestMessage = new Message <TRequest>(request);

            requestMessage.Properties.ReplyTo       = returnQueueName;
            requestMessage.Properties.CorrelationId = correlationId.ToString();
            requestMessage.Properties.Expiration    = (timeoutStrategy.GetTimeoutSeconds(requestType) * 1000).ToString();
            requestMessage.Properties.DeliveryMode  = (byte)(messageDeliveryModeStrategy.IsPersistent(requestType) ? 2 : 1);

            advancedBus.Publish(exchange, routingKey, false, false, requestMessage);
        }
Example #8
0
        public void DeclareExchangeWithAlternate()
        {
            const string alternate  = "alternate";
            const string bindingKey = "the-binding-key";

            var alternateExchange = advancedBus.ExchangeDeclare(alternate, ExchangeType.Direct);
            var originalExchange  = advancedBus.ExchangeDeclare("original", ExchangeType.Direct, alternateExchange: alternate);
            var queue             = advancedBus.QueueDeclare("my_queue");

            advancedBus.Bind(alternateExchange, queue, bindingKey);

            var message = Encoding.UTF8.GetBytes("Some message");

            advancedBus.Publish(originalExchange, bindingKey, false, false, new MessageProperties(), message);
        }
Example #9
0
 /// <summary>
 /// Publishes the Inquiry Response to MQ Exchange
 /// </summary>
 /// <param name="replyTo">Routing Key of queue to publish</param>
 /// <param name="message">TradeHub Inquiry Response message to be sent</param>
 public void PublishMessages(string replyTo, Message <InquiryResponse> message)
 {
     try
     {
         //using (var channel = _rabbitBus.OpenPublishChannel())
         {
             // Publish Messages to respective Queues
             _rabbitBus.Publish(_positionExchange, replyTo, true, false, message);
         }
     }
     catch (Exception exception)
     {
         Logger.Error(exception, _type.FullName, "PublishMessages");
     }
 }
Example #10
0
        private void FuturePublishInternal <T>(TimeSpan messageDelay, T message, string topic, string cancellationKey) where T : class
        {
            Preconditions.CheckNotNull(message, "message");
            Preconditions.CheckLess(messageDelay, MaxMessageDelay, "messageDelay");
            Preconditions.CheckNull(cancellationKey, "cancellationKey");

            var delay              = Round(messageDelay);
            var delayString        = delay.ToString(@"dd\_hh\_mm\_ss");
            var exchangeName       = conventions.ExchangeNamingConvention(typeof(T));
            var futureExchangeName = exchangeName + "_" + delayString;
            var futureQueueName    = conventions.QueueNamingConvention(typeof(T), delayString);
            var futureExchange     = advancedBus.ExchangeDeclare(futureExchangeName, ExchangeType.Topic);
            var futureQueue        = advancedBus.QueueDeclare(
                futureQueueName,
                perQueueMessageTtl: (int)delay.TotalMilliseconds,
                deadLetterExchange: exchangeName,
                deadLetterRoutingKey: setDeadLetterRoutingKey ? topic : null
                );

            advancedBus.Bind(futureExchange, futureQueue, topic);
            var easyNetQMessage = new Message <T>(message)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T))
                }
            };

            advancedBus.Publish(futureExchange, topic, false, easyNetQMessage);
        }
        /// <summary>
        /// 发布消息。自定义主题、交换机。EasyNetQ高级API
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="message"></param>
        /// <param name="topic"></param>
        /// <param name="exchangeName"></param>
        /// <returns></returns>
        public bool Publish <T>(T message, string topic, string exchangeName) where T : class, IBaseMqMessage
        {
            bool res = false;

            this.Logger(this.GetType(), "发布消息。自定义主题、交换机-Publish", () =>
            {
                if (message != null)
                {
                    if (!string.IsNullOrEmpty(topic))
                    {
                        IAdvancedBus advanced = bus.Advanced;
                        IExchange exchange    = advanced.ExchangeDeclare(exchangeName, ExchangeType.Topic);
                        advanced.Publish(exchange, topic, false, new Message <T>(message));
                    }
                    else
                    {
                        bus.Publish(message);
                    }
                    res = true;
                }
            }, e =>
            {
                res = false;
            });
            return(res);
        }
        public void PublishEvent <T>(T @event) where T : EventInfoBase
        {
            var routingKey = typeof(T).FullName;
            var message    = new Message <T>(@event);

            _bus.Publish(_exchange, routingKey, false, message);
        }
        private void FuturePublishInternal <T>(TimeSpan messageDelay, T message, string cancellationKey = null) where T : class
        {
            Preconditions.CheckNotNull(message, "message");
            Preconditions.CheckLess(messageDelay, MaxMessageDelay, "messageDelay");
            Preconditions.CheckNull(cancellationKey, "cancellationKey");

            var exchangeName       = conventions.ExchangeNamingConvention(typeof(T));
            var futureExchangeName = exchangeName + "_delayed";
            var queueName          = conventions.QueueNamingConvention(typeof(T), null);
            var futureExchange     = advancedBus.ExchangeDeclare(futureExchangeName, ExchangeType.Direct, delayed: true);
            var exchange           = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic);

            advancedBus.Bind(futureExchange, exchange, "#");
            var queue = advancedBus.QueueDeclare(queueName);

            advancedBus.Bind(exchange, queue, "#");
            var easyNetQMessage = new Message <T>(message)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(typeof(T)),
                    Headers      = new Dictionary <string,                                object>{
                        { "x-delay", (int)messageDelay.TotalMilliseconds }
                    }
                }
            };

            advancedBus.Publish(futureExchange, "#", false, false, easyNetQMessage);
        }
Example #14
0
        public virtual void Publish <T>(T message, Action <IPublishConfiguration> configure) where T : class
        {
            Preconditions.CheckNotNull(message, "message");
            Preconditions.CheckNotNull(configure, "configure");

            var configuration = new PublishConfiguration(conventions.TopicNamingConvention(typeof(T)));

            configure(configuration);

            var messageType     = typeof(T);
            var easyNetQMessage = new Message <T>(message)
            {
                Properties =
                {
                    DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType)
                }
            };

            if (configuration.Priority != null)
            {
                easyNetQMessage.Properties.Priority = configuration.Priority.Value;
            }
            if (configuration.Expires != null)
            {
                easyNetQMessage.Properties.Expiration = configuration.Expires.ToString();
            }

            var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, messageType, ExchangeType.Topic);

            advancedBus.Publish(exchange, configuration.Topic, false, easyNetQMessage);
        }
        public override void Send(RabbitMqMessageWrapper message)
        {
            var messageToSend = new Message <byte[]>(message.Bytes);

            messageToSend.Properties.Headers.Add("forward_exchange", Configuration.ExchangeName);
            _bus.Publish(_stampExchange, string.Empty, false, false, messageToSend);
        }
Example #16
0
        public void SetUp()
        {
            _applicationController = ContextRegistry.GetContext()["ApplicationController"] as ApplicationController;
            if (_applicationController != null)
            {
                _applicationController.StartServer();
            }

            // Initialize Advance Bus
            _advancedBus = RabbitHutch.CreateBus("host=localhost").Advanced;

            // Create a admin exchange
            _adminExchange = _advancedBus.ExchangeDeclare("marketdata_exchange", ExchangeType.Direct, true, false, true);

            // Create strategy admin Queue
            _strategyAdminQueue = _advancedBus.QueueDeclare("admin_queue", false, false, true, true);

            // Create strategy Tick Queue
            _tickQueue = _advancedBus.QueueDeclare("tick_queue", false, false, true, true);

            // Create strategy Live Bar Queue
            _liveBarQueue = _advancedBus.QueueDeclare("bar_queue", false, false, true, true);

            // Create strategy Tick Queue
            _historicQueue = _advancedBus.QueueDeclare("historic_queue", false, false, true, true);

            // Create admin Queue
            _logonQueue = _advancedBus.QueueDeclare("marketdata_engine_logon_queue", false, false, true, true);

            // Create inquiry Queue
            _inquiryQueue = _advancedBus.QueueDeclare("inquiry_queue", false, false, true, true);

            // Bind Strategy Admin Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _strategyAdminQueue, "admin.strategy.key");

            // Bind Strategy Tick Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _tickQueue, "tick.strategy.key");

            // Bind Strategy Live Bar Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _liveBarQueue, "bar.strategy.key");

            // Bind Strategy Historic Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _historicQueue, "historic.strategy.key");

            // Bind Admin Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _inquiryQueue, "inquiry.strategy.key");

            // Bind Admin Queue to already initialized Exchange with the specified Routing Key
            _advancedBus.Bind(_adminExchange, _logonQueue, "marketdata.engine.login");

            var appInfoMessage = new Message <Dictionary <string, string> >(appInfo);

            appInfoMessage.Properties.AppId = "test_app_id";
            string routingKey = "marketdata.engine.appinfo";

            //using (var channel = _advancedBus.OpenPublishChannel())
            {
                _advancedBus.Publish(_adminExchange, routingKey, true, false, appInfoMessage);
            }
        }
Example #17
0
 private void Handle(TaskArguments taskArguments)
 {
     if (_finishedProductService.IsReady(taskArguments))
     {
         //if product ready publish it
         _bus.Publish(_finishedProductsExchange, String.Empty, false, new Message <TaskArguments>(taskArguments));
     }
 }
Example #18
0
        public void Publish <TMessage>(TMessage message) where TMessage : class
        {
            // Serialization to JSON happens implicitely here!
            var msg = new Message <TMessage>(message);

            msg.Properties.AppId = "Sample EasyNetQ Publisher";
            advancedBus.Publish(Exchange.GetDefault(), QUEUE_NAME, false, msg);
        }
 private void Handle(MessageMetadata message)
 {
     if (_finishedProductService.IsReady(message))
     {
         //if product ready publish it
         _bus.Publish(_finishedProductsExchange, String.Empty, false, new Message <MessageMetadata>(message));
     }
 }
Example #20
0
        /// <summary>
        /// Publishes received message to respective queue
        /// </summary>
        /// <param name="notification">notification to be sent to server</param>
        /// <param name="routingKey">routing key to send message to respective queue</param>
        private void PublishNotifications(OrderNotification notification, string routingKey)
        {
            // Wrap notification in EasyNetQ message interface
            IMessage <OrderNotification> message = new Message <OrderNotification>(notification);

            // Send message to queue
            _advancedBus.Publish(_exchange, routingKey, true, false, message);
        }
Example #21
0
        protected virtual void RequestPublish <TRequest>(TRequest request, string routingKey, string returnQueueName, Guid correlationId)
            where TRequest : class
        {
            var requestType = typeof(TRequest);
            var exchange    = publishExchangeDeclareStrategy.DeclareExchange(conventions.RpcRequestExchangeNamingConvention(requestType), ExchangeType.Direct);

            var requestMessage = new Message <TRequest>(request)
            {
                Properties =
                {
                    ReplyTo       = returnQueueName,
                    CorrelationId = correlationId.ToString(),
                    Expiration    = (timeoutStrategy.GetTimeoutSeconds(requestType) * 1000).ToString(),
                    DeliveryMode  = messageDeliveryModeStrategy.GetDeliveryMode(requestType)
                }
            };

            advancedBus.Publish(exchange, routingKey, false, requestMessage);
        }
Example #22
0
        public void Publish <TMessage>(TMessage message) where TMessage : class
        {
            // Serialization to JSON happens implicitely here!
            var msg = new Message <TMessage>(message);

            msg.Properties.AppId = "Sample EasyNetQ Publisher";
            var routingKey = typeof(TMessage).FullName;

            advancedBus.Publish(exchange, routingKey, false, msg);
        }
Example #23
0
        private void PublishInternal <T>(IExchange exchange, string queueName, T message) where T : class
        {
            //Wrap message in IMessage
            IMessage <T> wrappedMessage = new Message <T>(message);

            lock (_locker)
            {
                _advancedBus.Publish(exchange, queueName, false, wrappedMessage);
            }
        }
        /// <summary>
        /// Publishes Inquiry messages to the MQ Exchange
        /// </summary>
        private void PublishMessages(Message <InquiryMessage> inquiryMessage, string routingKey)
        {
            try
            {
                // using (var channel = _advancedBus.OpenPublishChannel())
                {
                    // Publish Messages to respective Queues
                    _advancedBus.Publish(_exchange, routingKey, true, false, inquiryMessage);

                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("Inquiry request published", _type.FullName, "PublishMessages");
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "PublishMessages");
            }
        }
Example #25
0
        public void Publish <T>(T message, string topic) where T : class
        {
            GuardHelper.ArgumentNotNull(() => message);

            var         messageType   = typeof(T);
            Message <T> rabbitMessage = GetRabbitMessage(message, messageType);
            var         exchange      = publishExchangeDeclareStrategy.DeclareExchange(
                advancedBus, messageType, ExchangeType.Topic);

            advancedBus.Publish(exchange, topic, rabbitMessage);
        }
        public void InquiryMessageTestCase()
        {
            bool inquiryReceived = false;
            var  inquiryEvent    = new ManualResetEvent(false);

            _positionMqServer.InquiryRequestReceived += delegate(IMessage <InquiryMessage> obj)
            {
                inquiryReceived = true;
                inquiryEvent.Set();
            };

            // using (var channel = _advancedBus.OpenPublishChannel())
            {
                IMessage <InquiryMessage> message = new Message <InquiryMessage>(new InquiryMessage());
                _advancedBus.Publish(_adminExchange, "position.engine.inquiry", true, false, message);
            }

            inquiryEvent.WaitOne(10000, false);
            Assert.AreEqual(true, inquiryReceived, "Inquiry Received");
        }
        public override void Send(RabbitMqMessageWrapper message)
        {
            var mongoRabbitMessage = new MongoRabbitMessage()
            {
                Id      = GetNewMessageId(),
                Content = message.Bytes
            };
            var rabbitMessage = new Message <MongoRabbitMessage>(mongoRabbitMessage);

            _bus.Publish(_receiveExchange, String.Empty, false, false, rabbitMessage);
        }
Example #28
0
        /// <summary>
        /// Called when notified by Heartbeat Handler to send heartbeat response from MDE
        /// </summary>
        /// <param name="heartbeat">TradeHub Heartbeat Message</param>
        private void OnResponseHeartbeat(HeartbeatMessage heartbeat)
        {
            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("Publishing Heartbeat response: " + heartbeat, _type.FullName, "OnResponseHeartbeat");
                }

                // Generate EasyNetQ Message for publishing
                IMessage <HeartbeatMessage> heartbeatMessage = new Message <HeartbeatMessage>(heartbeat);

                // Publish Messages to respective Queues
                _easyNetQBus.Publish(_exchange, heartbeat.ReplyTo, true, false, heartbeatMessage);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "OnResponseHeartbeat");
            }
        }
        private static void SendAuthResponse(IAdvancedBus advancedBus, IExchange exchange)
        {
            // Send auth success
            // TODO: Check the actual authentication stuff
            var responseEvent = new Event();
            responseEvent.Type = Event.EventType.response;
            var response = new AuthenticationResponse();
            response.Success = true;
            responseEvent.Content = response;
            var responseMessage = new Message<Event>(responseEvent);

            advancedBus.Publish(exchange, "Have.Auth.v1", false, false, responseMessage);
        }
Example #30
0
        /// <summary>
        /// 메세시 게시
        /// </summary>
        /// <param name="messageConfig">메세지 게시 설정</param>
        /// <param name="message">게시할 메세지</param>
        public void Publish(MessageConfiguration messageConfig, byte[] message)
        {
            var exchange = new Exchange(messageConfig.ExchangeName);

            advancedBus.Publish(exchange,
                                messageConfig.RoutingKey,
                                false,
                                new MessageProperties()
            {
                DeliveryMode = MessageDeliveryMode.Persistent
            },
                                message);
        }
        private static void SendAuthResponse(IAdvancedBus advancedBus, IExchange exchange)
        {
            // Send auth success
            // TODO: Check the actual authentication stuff
            var responseEvent = new Event();

            responseEvent.Type = Event.EventType.response;
            var response = new AuthenticationResponse();

            response.Success      = true;
            responseEvent.Content = response;
            var responseMessage = new Message <Event>(responseEvent);

            advancedBus.Publish(exchange, "Have.Auth.v1", false, false, responseMessage);
        }