public void Start()
        {
            _bus = BusFactory.CreateAdvancedBus(ConfigurationReader.WorkflowSender);
            var senderQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Sender");
            var senderExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Sender", ExchangeType.Fanout);
            _bus.Bind(senderExchange, senderQueue, string.Empty);

            var receiverQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Receiver");
            var receiverExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Receiver", ExchangeType.Fanout);
            _bus.Bind(receiverExchange, receiverQueue, string.Empty);

            _bus.Consume(senderQueue, x => x
                .Add<SendRequestToDataProviderCommand>(
                    (message, info) => new SenderCauseFailureConsumers<SendRequestToDataProviderCommand>(message))
                .Add<GetResponseFromDataProviderCommmand>(
                    (message, info) => new SenderCauseFailureConsumers<GetResponseFromDataProviderCommmand>(message))
                .Add<CreateTransactionCommand>(
                    (message, info) => new SenderCauseFailureConsumers<CreateTransactionCommand>(message))
                .Add<ReceiveEntryPointRequest>(
                    (message, info) => new SenderCauseFailureConsumers<ReceiveEntryPointRequest>(message))
                .Add<ReturnEntryPointResponse>(
                    (message, info) => new SenderCauseFailureConsumers<ReturnEntryPointResponse>(message))
                .Add<RaisingSecurityFlagCommand>(
                    (message, info) => new SenderCauseFailureConsumers<RaisingSecurityFlagCommand>(message))
                .Add<ConfiguringDataProviderCommand>(
                    (message, info) => new SenderCauseFailureConsumers<ConfiguringDataProviderCommand>(message))
                .Add<TransformingDataProviderResponseCommand>(
                    (message, info) => new SenderCauseFailureConsumers<TransformingDataProviderResponseCommand>(message))
                .Add<ErrorInDataProviderCommand>(
                    (message, info) => new SenderCauseFailureConsumers<ErrorInDataProviderCommand>(message))
                .Add<StartingCallCommand>(
                    (message, info) => new SenderCauseFailureConsumers<StartingCallCommand>(message))
                .Add<EndingCallCommand>((message, info) => new SenderCauseFailureConsumers<EndingCallCommand>(message)));

            _bus.Consume(receiverQueue, x => x
                .Add<RequestToDataProvider>(
                    (message, info) => new ReceiverCauseFailureConsumers<RequestToDataProvider>(message))
                .Add<EntryPointReceivedRequest>(
                    (message, info) => new ReceiverCauseFailureConsumers<EntryPointReceivedRequest>(message))
                .Add<ResponseFromDataProvider>(
                    (message, info) => new ReceiverCauseFailureConsumers<ResponseFromDataProvider>(message))
                .Add<EntryPointReturnedResponse>(
                    (message, info) => new ReceiverCauseFailureConsumers<EntryPointReturnedResponse>(message))
                //.Add<BillTransactionMessage>(
                //    (message, info) => new ReceiverConsumers<BillTransactionMessage>(message))
                .Add<SecurityFlagRaised>(
                    (message, info) => new ReceiverCauseFailureConsumers<SecurityFlagRaised>(message))
                .Add<DataProviderCallEnded>(
                    (message, info) => new ReceiverCauseFailureConsumers<DataProviderCallEnded>(message))
                .Add<DataProviderCallStarted>(
                    (message, info) => new ReceiverCauseFailureConsumers<DataProviderCallStarted>(message))
                .Add<DataProviderError>(
                    (message, info) => new ReceiverCauseFailureConsumers<DataProviderError>(message))
                .Add<DataProviderResponseTransformed>(
                    (message, info) => new ReceiverCauseFailureConsumers<DataProviderResponseTransformed>(message))
                .Add<DataProviderConfigured>(
                    (message, info) => new ReceiverCauseFailureConsumers<DataProviderConfigured>(message)));

            _log.DebugFormat("Data Provider Command Processor Service Started");
        }
Example #2
0
        public void SetUp()
        {
            mockBuilder = new MockBuilder();
            advancedBus = mockBuilder.Bus.Advanced;

            var exchange = new Exchange("my_exchange");
            var queue    = new Topology.Queue("my_queue", false);

            binding = advancedBus.Bind(exchange, queue, "my_routing_key");
        }
Example #3
0
        protected virtual string SubscribeToResponse <TRequest, TResponse>()
            where TResponse : class
        {
            var responseType = typeof(TResponse);
            var rpcKey       = new RpcKey {
                Request = typeof(TRequest), Response = responseType
            };
            string queueName;

            if (responseQueues.TryGetValue(rpcKey, out queueName))
            {
                return(queueName);
            }
            lock (responseQueuesAddLock)
            {
                if (responseQueues.TryGetValue(rpcKey, out queueName))
                {
                    return(queueName);
                }

                var queue = advancedBus.QueueDeclare(
                    conventions.RpcReturnQueueNamingConvention(),
                    passive: false,
                    durable: false,
                    exclusive: true,
                    autoDelete: true);

                var exchange = DeclareRpcExchange(conventions.RpcResponseExchangeNamingConvention(responseType));

                advancedBus.Bind(exchange, queue, queue.Name);

                advancedBus.Consume <TResponse>(queue, (message, messageReceivedInfo) => Task.Factory.StartNew(() =>
                {
                    ResponseAction responseAction;
                    if (responseActions.TryRemove(message.Properties.CorrelationId, out responseAction))
                    {
                        responseAction.OnSuccess(message);
                    }
                }));
                responseQueues.TryAdd(rpcKey, queue.Name);
                return(queue.Name);
            }
        }
        public When_a_queue_is_unbound_from_an_exchange()
        {
            mockBuilder = new MockBuilder();
            advancedBus = mockBuilder.Bus.Advanced;

            var exchange = new Exchange("my_exchange");
            var queue    = new Topology.Queue("my_queue", false);

            binding = advancedBus.Bind(exchange, queue, "my_routing_key");
            advancedBus.BindingDelete(binding);
        }
Example #5
0
        public async Task Handle(CustomerWasCreated notification, CancellationToken cancellationToken)
        {
            var message = new Message <ICustomerWasCreated>(notification);

            var exchange = _bus.ExchangeDeclare("customer-was-created", ExchangeType.Fanout);
            var queue    = _bus.QueueDeclare("customer-was-created");

            _bus.Bind(exchange, queue, "");

            await _bus.PublishAsync <ICustomerWasCreated>(exchange, "", true, message);
        }
Example #6
0
        public async Task PublishPayment(Payment message)
        {
            var queueExhange = nameof(Payment);
            var queue2       = _bus.QueueDeclare(queueExhange);
            var exchange     = _bus.ExchangeDeclare(queueExhange, ExchangeType.Topic);

            _bus.Bind(exchange, queue2, "A.*");

            var topic       = $"ProjectId.CabinId";
            var yourMessage = new Message <string>(JsonConvert.SerializeObject(message));
            await _bus.PublishAsync(exchange, "A.*", true, yourMessage);
        }
        public When_a_queue_is_bound_to_an_exchange_with_headers()
        {
            mockBuilder = new MockBuilder();
            advancedBus = mockBuilder.Bus.Advanced;

            var exchange = new Exchange("my_exchange");
            var queue    = new Topology.Queue("my_queue", false);

            binding = advancedBus.Bind(exchange, queue, "my_routing_key", new Dictionary <string, object> {
                ["header1"] = "value1"
            });
        }
Example #8
0
        private static void CreateConsumers(IDependencyResolver resolver, IAdvancedBus advancedBus, ExchangeItem exchangeItem)
        {
            if (exchangeItem.RabbitExchange == null)
            {
                throw new ArgumentException("rabbit exchange is null`");
            }

            foreach (var income in exchangeItem.In)
            {
                var queue = advancedBus.QueueDeclare(string.Format("{0}.{1}", exchangeItem.Name, income.Key));
                advancedBus.Bind(exchangeItem.RabbitExchange, queue, income.Key);

                var messageType = ReflectionHelper.ResolveType(income.Type);

                if (messageType == null)
                {
                    throw new Exception("no such message type");
                }

                Type consType     = ReflectionHelper.ResolveType(income.React);
                var  consumer     = resolver.Resolve(consType);
                var  endpointInfo = EndpointInfoFactory.Create(advancedBus, exchangeItem.RabbitExchange, income.Name, income.Key);

                var handlerReg = GetHandlerRegistration(endpointInfo, consumer, messageType);


                IList <object> consumeInvokeParams = new List <object>();
                consumeInvokeParams.Add(queue);

                var action = ConsumeWrapperProvider.GetConsumeActionWrapper(handlerReg, resolver);
                consumeInvokeParams.Add(action);

                if (!ConsumerActions.TryAdd(consumer.GetType(), action))
                {
                    Logger.Warn("can't add consumer handler for {0}", consumer.GetType().ToString());
                }

                Action <IConsumerConfiguration> consConf = configuration => configuration.WithPrefetchCount(exchangeItem.PrefetchCount);
                consumeInvokeParams.Add(consConf);

                //NOTE: Such ugly shit to get generic overloaded method
                var sbConsume = typeof(IAdvancedBus).GetMethods().Where(x => x.Name == "Consume").Select(m => new
                {
                    Method = m,
                    Params = m.GetParameters(),
                    Args   = m.GetGenericArguments()
                }).Where(x => x.Params.Length == 3 && x.Args.Length == 0 &&
                         x.Params[1].ParameterType.Name == action.GetType().Name)
                                .Select(x => x.Method)
                                .First();
                sbConsume.Invoke(advancedBus, consumeInvokeParams.ToArray());
            }
        }
        public void Start()
        {
            var finishedProductExchanger = _bus.ExchangeDeclare(_settings.FinishedProductExchanger, ExchangeType.Fanout);

            _retryExchanger = _bus.ExchangeDeclare("FinifshedProductDelayRetryForNotify", ExchangeType.Fanout, delayed: true);

            var queue = _bus.QueueDeclare("ProductQueue");

            _bus.Bind(finishedProductExchanger, queue, "*");
            _bus.Bind(_retryExchanger, queue, "*");

            _bus.Consume(queue, registration => registration
                         .Add <MessageMetadata>((message, info) =>
            {
                Process(message.Body);
            })
                         .Add <RedeliveribleMessage>((message, info) =>
            {
                ProcessWithRetry(message.Body.Message, message.Body.Subscriptions, message.Body.DeliveryCount);
            }));
        }
Example #10
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);
            }
        }
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            var exchange = _bus.ExchangeDeclare(typeof(SampleMessage).FullName, ExchangeType.Topic);

            _bus.Bind(exchange, _queue, "#");
            _bus.Consume <SampleMessage>(_queue, (message, info) =>
            {
                Console.WriteLine("Message consumed:");
                Console.WriteLine(message.Body.Text);
            });

            return(Task.CompletedTask);
        }
        public async Task RegisterHandlerAsync(string route, Func <Message, CancellationToken, Task> handler, CancellationToken cancellationToken = default)
        {
            var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            var exchange = await DeclareBusExchangeAsync(cts.Token);

            var queue = _bus.QueueDeclare(route);

            _bus.Bind(exchange, queue, route);

            // TODO token passed into handler?
            _bus.Consume(queue, (body, props, info) => handler(MessageHelpers.FromArgs(body, props), CancellationToken.None));
        }
Example #13
0
        public void Start()
        {
            var infExchanger = _bus.ExchangeDeclare(ExchangerNames.Tasks, ExchangeType.Topic);

            _finishedProductsExchange = _bus.ExchangeDeclare(_settings.FinishedProductExchanger, ExchangeType.Fanout);

            var queue = _bus.QueueDeclare("CheckProductReadyQueue");

            _bus.Bind(infExchanger, queue, "*");

            _bus.Consume(queue, registration => registration
                         .Add <TaskArguments>((message, info) => { ConsumeAndProcess(message.Body); })
                         );
        }
Example #14
0
        public void TestQueueWay4()
        {
            IAdvancedBus bus = RabbitHutch.CreateBus(ConfigurationAppSetting.RabbitMQHost, reg => reg.Register <IEasyNetQLogger>(log => new Log4NetLogger())).Advanced;
            IExchange    ex  = bus.ExchangeDeclare("JinRi.Notify.Test.TestQueueWay4Ex", "topic");
            IQueue       qu1 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay4Queue1");
            IQueue       qu2 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay4Queue2");
            IQueue       qu3 = bus.QueueDeclare("JinRi.Notify.Test.TestQueueWay4Queue3");
            IBinding     bi1 = bus.Bind(ex, qu1, "*.0.*");
            IBinding     bi2 = bus.Bind(ex, qu2, "*.1.*");
            IBinding     bi3 = bus.Bind(ex, qu3, "*.2.*");

            for (int i = 0; i < 100; i++)
            {
                int md = i % 3;
                bus.Publish <string>(ex, "a." + md.ToString() + ".b", false, false, new Message <string>(i.ToString()));
            }

            bus.Consume <string>(qu1, (a, b) =>
            {
                Debug.WriteLine(a.Body);
            });
            Thread.Sleep(5000);
        }
Example #15
0
        public void Start()
        {
            var finishedProductExchanger = _bus.ExchangeDeclare(_settings.FinishedProductExchanger, ExchangeType.Fanout);

            var queue = _bus.QueueDeclare("ProductQueue");

            _bus.Bind(finishedProductExchanger, queue, "*");

            _bus.Consume(queue, registration => registration
                         .Add <TaskArguments>((message, info) =>
            {
                Process(message.Body);
            }));
        }
Example #16
0
        public void Init()
        {
            try
            {
                _waitForMessage.Reset();

                //connect
                Stopwatch w = new Stopwatch();
                w.Start();
                _advancedBus = RabbitHutch.CreateBus(
                    _connectionConfiguration,
                    new AdvancedBusEventHandlers(
                        connected: OnRabbitConnectionStateChanged,
                        disconnected: OnRabbitConnectionStateChanged),
                    RegisterServices
                    ).Advanced;
                w.Stop();
                Console.WriteLine($"Oppkobling: {w.ElapsedMilliseconds} ms");

                //SystemX
                _systemXExchange = GetExchange("exchange.to.SystemX.from.TransMed");
                _systemXQueue    = GetQueue("queue.to.SystemX.from.TransMed");
                _advancedBus.Bind(_systemXExchange, _systemXQueue, "#");

                _transMedExchange = GetExchange("exchange.to.TransMed.from.SystemX");
                _transMedQueue    = GetQueue("queue.to.TransMed.from.SystemX");
                _advancedBus.Bind(_transMedExchange, _transMedQueue, "#");


                _rpc = new SystemXRpc(_advancedBus);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error on init: " + e);
                throw;
            }
        }
Example #17
0
        public virtual IDisposable Respond <TRequest, TResponse>(Func <TRequest, Task <TResponse> > responder)
            where TRequest : class
            where TResponse : class
        {
            Preconditions.CheckNotNull(responder, "responder");

            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));

            var exchange = advancedBus.ExchangeDeclare(conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);
            var queue    = advancedBus.QueueDeclare(routingKey);

            advancedBus.Bind(exchange, queue, routingKey);

            return(advancedBus.Consume <TRequest>(queue, (requestMessage, messageRecievedInfo) => ExecuteResponder(responder, requestMessage)));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="MailUserDispatcher"/> class.
        /// </summary>
        /// <param name="bus"></param>
        /// <param name="config"></param>
        /// <param name="userTestResultRepository"></param>
        public MailUserDispatcher(
            IBus bus,
            IOptions <SendEmailConfig> config,
            IUserTestResultRepository userTestResultRepository,
            ITestResultRepository testResultRepository)
        {
            _userTestResultRepository = userTestResultRepository;
            _testResultRepository     = testResultRepository;
            _config      = config.Value;
            _advancedBus = bus.Advanced;

            var queue = _advancedBus.QueueDeclare(_config.EmailQueue);

            _exchange = _advancedBus.ExchangeDeclare(_config.EmailExchange, ExchangeType.Direct);
            _advancedBus.Bind(_exchange, queue, _config.RoutingKey);
        }
Example #19
0
        private IExchange DeclareVersionedExchanges(IAdvancedBus advancedBus, IConventions conventions, MessageVersionStack messageVersions, string exchangeType)
        {
            IExchange destinationExchange = null;

            while (!messageVersions.IsEmpty())
            {
                var messageType    = messageVersions.Pop();
                var exchangeName   = conventions.ExchangeNamingConvention(messageType);
                var sourceExchange = DeclareExchange(advancedBus, exchangeName, exchangeType);
                if (destinationExchange != null)
                {
                    advancedBus.Bind(sourceExchange, destinationExchange, "#");
                }
                destinationExchange = sourceExchange;
            }
            return(destinationExchange);
        }
        private IExchange DeclareVersionedExchanges( IAdvancedBus advancedBus, IConventions conventions, MessageVersionStack messageVersions, string exchangeType )
        {
            // This works because the message version stack is LIFO from most superseded message type to the actual message type
            IExchange destinationExchange = null;
            while( !messageVersions.IsEmpty() )
            {
                var messageType = messageVersions.Pop();
                var exchangeName = conventions.ExchangeNamingConvention( messageType );
                var sourceExchange = DeclareExchange( advancedBus, exchangeName, exchangeType );

                if( destinationExchange != null )
                    advancedBus.Bind( sourceExchange, destinationExchange, "#" );

                destinationExchange = sourceExchange;
            }
            return destinationExchange;
        }
Example #21
0
        public IDisposable Respond <TRequest, TResponse>(Func <TRequest, Task <TResponse> > responder)
            where TRequest : class
            where TResponse : class
        {
            Preconditions.CheckNotNull(responder, "responder");

            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));

            var exchange = advancedBus.ExchangeDeclare(conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);
            var queue    = advancedBus.QueueDeclare(routingKey);

            advancedBus.Bind(exchange, queue, routingKey);

            return(advancedBus.Consume <TRequest>(queue, (requestMessage, messageRecievedInfo) =>
            {
                var tcs = new TaskCompletionSource <object>();

                responder(requestMessage.Body).ContinueWith(task =>
                {
                    if (task.IsFaulted)
                    {
                        if (task.Exception != null)
                        {
                            var body = Activator.CreateInstance <TResponse>();
                            var responseMessage = new Message <TResponse>(body);
                            responseMessage.Properties.Headers.Add(IsFaultedKey, true);
                            responseMessage.Properties.Headers.Add(ExceptionMessageKey, task.Exception.InnerException.Message);
                            responseMessage.Properties.CorrelationId = requestMessage.Properties.CorrelationId;

                            advancedBus.Publish(Exchange.GetDefault(), requestMessage.Properties.ReplyTo, false, false, responseMessage);
                            tcs.SetException(task.Exception);
                        }
                    }
                    else
                    {
                        var responseMessage = new Message <TResponse>(task.Result);
                        responseMessage.Properties.CorrelationId = requestMessage.Properties.CorrelationId;

                        advancedBus.Publish(Exchange.GetDefault(), requestMessage.Properties.ReplyTo, false, false, responseMessage);
                        tcs.SetResult(null);
                    }
                });

                return tcs.Task;
            }));
        }
        /// <summary>
        /// Initializes RabbitMQ Queue
        /// </summary>
        private IQueue InitializeQueue(IExchange exchange, string queueName, string routingKey)
        {
            try
            {
                // Initialize specified Queue
                IQueue queue = _easyNetQBus.QueueDeclare(queueName, false, false, true, true);

                // Bind Queue to already initialized Exchange with the specified Routing Key
                _easyNetQBus.Bind(exchange, queue, routingKey);
                return(queue);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "InitializeQueue");
                return(null);
            }
        }
Example #23
0
        public async Task Publish(string mes)
        {
            var queueExhange = nameof(PublishMessage);
            var queue2       = _bus.QueueDeclare(queueExhange);
            var exchange     = _bus.ExchangeDeclare(queueExhange, ExchangeType.Topic);

            _bus.Bind(exchange, queue2, "A.*");
            var newMessage = new PublishMessage()
            {
                Text = "Hello"
            };
            var topic       = $"ProjectId.CabinId";
            var yourMessage = new Message <string>(JsonConvert.SerializeObject(new PublishMessage {
                Text = mes
            }));
            await _bus.PublishAsync(exchange, "A.*", true, yourMessage);
        }
Example #24
0
        public virtual ISubscriptionResult SubscribeAsync <T>(string subscriptionId, Func <T, Task> onMessage, Action <ISubscriptionConfiguration> configure) where T : class
        {
            Preconditions.CheckNotNull(subscriptionId, "subscriptionId");
            Preconditions.CheckNotNull(onMessage, "onMessage");
            Preconditions.CheckNotNull(configure, "configure");

            var configuration = new SubscriptionConfiguration(connectionConfiguration.PrefetchCount);

            configure(configuration);

            var queueName    = configuration.QueueName ?? conventions.QueueNamingConvention(typeof(T), subscriptionId);
            var exchangeName = conventions.ExchangeNamingConvention(typeof(T));

            var queue = advancedBus.QueueDeclare(
                queueName,
                autoDelete: configuration.AutoDelete,
                durable: configuration.Durable,
                expires: configuration.Expires,
                maxPriority: configuration.MaxPriority,
                maxLength: configuration.MaxLength,
                maxLengthBytes: configuration.MaxLengthBytes,
                consumerRepariable: true);
            var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic);

            foreach (var topic in configuration.Topics.DefaultIfEmpty("#"))
            {
                advancedBus.Bind(exchange, queue, topic);
            }

            var consumerCancellation = advancedBus.Consume <T>(
                queue,
                (message, messageReceivedInfo) => onMessage(message.Body),
                x =>
            {
                x.WithPriority(configuration.Priority)
                .WithCancelOnHaFailover(configuration.CancelOnHaFailover)
                .WithPrefetchCount(configuration.PrefetchCount);
                if (configuration.IsExclusive)
                {
                    x.AsExclusive();
                }
            });

            return(new SubscriptionResult(exchange, queue, consumerCancellation));
        }
        public void StartCalculation()
        {
            var calculationId = InitializeDistributedCalculation();
            var exchange      = _bus.ExchangeDeclare("fibonacciExchange", "direct", durable: true, autoDelete: true);

            var queue = _bus.QueueDeclare();

            var routingId = calculationId.ToString();

            _bus.Bind(exchange, queue, routingId);

            _bus.Consume(queue, (bytes, properties, info) =>
            {
                CalculateNextNumber(bytes, calculationId);
            });

            SendNumber(InitialFibonacciNumber, calculationId);
        }
Example #26
0
        public IDisposable Respond <TRequest, TResponse>(Func <TRequest, Task <TResponse> > responder, Action <IResponderConfiguration> configure) where TRequest : class where TResponse : class
        {
            Preconditions.CheckNotNull(responder, "responder");
            Preconditions.CheckNotNull(configure, "configure");
            var configuration = new ResponderConfiguration(connectionConfiguration.PrefetchCount);

            configure(configuration);

            var routingKey = conventions.RpcRoutingKeyNamingConvention(typeof(TRequest));

            var exchange = advancedBus.ExchangeDeclare(conventions.RpcExchangeNamingConvention(), ExchangeType.Direct);
            var queue    = advancedBus.QueueDeclare(routingKey);

            advancedBus.Bind(exchange, queue, routingKey);

            return(advancedBus.Consume <TRequest>(queue, (requestMessage, messageRecievedInfo) => ExecuteResponder(responder, requestMessage),
                                                  c => c.WithPrefetchCount(configuration.PrefetchCount)));
        }
Example #27
0
        public IExchange DeclareExchange(Type messageType, string exchangeType)
        {
            var sourceExchangeName = conventions.ExchangeNamingConvention(messageType);
            var sourceExchange     = DeclareExchange(sourceExchangeName, exchangeType);
            var interfaces         = messageType.GetInterfaces();

            foreach (var @interface in interfaces)
            {
                var destinationExchangeName = conventions.ExchangeNamingConvention(@interface);
                var destinationExchange     = DeclareExchange(destinationExchangeName, exchangeType);
                if (destinationExchange != null)
                {
                    advancedBus.Bind(sourceExchange, destinationExchange, "#");
                }
            }

            return(sourceExchange);
        }
Example #28
0
        public override void StartListening()
        {
            _receiveexchange = _bus.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout);
            _stampExchange   = _bus.ExchangeDeclare(Configuration.StampExchangeName, "x-stamp");

            _queue = Configuration.QueueName == null
                        ? _bus.QueueDeclare()
                        : _bus.QueueDeclare(Configuration.QueueName);

            _bus.Bind(_receiveexchange, _queue, "#");
            _bus.Consume <RabbitMqMessageWrapper>(_queue,
                                                  (msg, messageReceivedInfo) =>
            {
                var message = msg.Body;
                message.Id  = (ulong)Convert.ToInt64(msg.Properties.Headers["stamp"]);
                return(Task.Factory.StartNew(() => OnMessage(message)));
            });
        }
        public override void StartListening()
        {
            _receiveExchange = _bus.ExchangeDeclare(Configuration.ExchangeName, ExchangeType.Fanout);
            _queue           = Configuration.QueueName == null
                        ? _bus.QueueDeclare()
                        : _bus.QueueDeclare(Configuration.QueueName);

            _bus.Bind(_receiveExchange, _queue, "#");
            _bus.Consume <MongoRabbitMessage>(_queue, (message, info) =>
            {
                var wrapperMsg = new RabbitMqMessageWrapper()
                {
                    Id    = message.Body.Id,
                    Bytes = message.Body.Content
                };
                return(Task.Factory.StartNew(() => OnMessage(wrapperMsg)));
            });
        }
Example #30
0
        public IDisposable SubscribeAsync
        (
            [NotNull] Type type,
            [NotNull] string subscriptionId,
            [NotNull] Func <object, Task> onMessage,
            [NotNull] Action <IAdvancedSubscriptionConfiguration> configure
        )
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (subscriptionId == null)
            {
                throw new ArgumentNullException("subscriptionId");
            }
            if (onMessage == null)
            {
                throw new ArgumentNullException("onMessage");
            }
            if (configure == null)
            {
                throw new ArgumentNullException("configure");
            }

            var configuration = new AdvancedSubscriptionConfiguration();

            configure(configuration);

            var queueName    = conventions.QueueNamingConvention(type, subscriptionId);
            var exchangeName = conventions.ExchangeNamingConvention(type);

            var queue    = advancedBus.QueueDeclare(queueName, durable: configuration.Durable, autoDelete: configuration.AutoDelete);
            var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic);

            foreach (var topic in configuration.Topics.AtLeastOneWithDefault("#"))
            {
                advancedBus.Bind(exchange, queue, topic);
            }

            Func <IMessage <object>, MessageReceivedInfo, Task> oms = (message, messageRecievedInfo) => onMessage(message.Body);

            return(advancedBus.Consume(queue, x => x.Add(oms)));
        }
        private IExchange DeclareVersionedExchanges(IAdvancedBus advancedBus, IConventions conventions, MessageVersionStack messageVersions, string exchangeType)
        {
            // This works because the message version stack is LIFO from most superseded message type to the actual message type
            IExchange destinationExchange = null;

            while (!messageVersions.IsEmpty())
            {
                var messageType    = messageVersions.Pop();
                var exchangeName   = conventions.ExchangeNamingConvention(messageType);
                var sourceExchange = DeclareExchange(advancedBus, exchangeName, exchangeType);

                if (destinationExchange != null)
                {
                    advancedBus.Bind(sourceExchange, destinationExchange, "#");
                }

                destinationExchange = sourceExchange;
            }
            return(destinationExchange);
        }
Example #32
0
        public void RegisterConsumer <T>(IEventConsumer <T> consumer) where T : EventInfoBase
        {
            var queue      = _bus.QueueDeclare(GetQueueNameForConsumer(consumer));
            var routingKey = GetRoutingKeyForEvent <T>();

            _bus.Bind(_mainExchange, queue, routingKey);
            _bus.Consume <T>(queue, (message, info) =>
                             Task.Factory.StartNew(() =>
            {
                try
                {
                    consumer.Consume(message.Body);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
                                                   ));
        }
        public void Start()
        {
            Log.Debug("Starting Cache Worker");
            var properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "RemoteServer";


            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";


            properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz";
            properties["quartz.plugin.xml.fileNames"] = "jobs.xml";

            ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties);
            _scheduler = schedulerFactory.GetScheduler();
            _scheduler.JobFactory = new JobFactory(_container);

            _scheduler.Start();

            _bus = _container.Resolve<IAdvancedBus>();
            var receiverQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Cache.Receiver");
            var receiverExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Cache.Receiver", ExchangeType.Fanout);
            _bus.Bind(receiverExchange, receiverQueue, string.Empty);

            _bus.Consume(receiverQueue, q => q
                .Add<ClearCacheCommand>(
                (message, info) => new ReceiverConsumers<ClearCacheCommand>(message, _container))
                .Add<RefreshCacheCommand>(
                (message, info) => new ReceiverConsumers<RefreshCacheCommand>(message, _container))
                .Add<RestartCacheDataStoreCommand>(
                (message, info) => new ReceiverConsumers<RestartCacheDataStoreCommand>(message, _container)));

            Log.Debug("Cache Worker has started");
        }
        public void SetUp()
        {
            mockBuilder = new MockBuilder();
            advancedBus = mockBuilder.Bus.Advanced;

            var exchange = new Exchange("my_exchange");
            var queue = new Topology.Queue("my_queue", false);
            binding = advancedBus.Bind(exchange, queue, "my_routing_key");
            advancedBus.BindingDelete(binding);
        }
        public void Start()
        {
            _log.DebugFormat("Data Provider Command Processor Service being fired up...");

            var container = new WindsorContainer().Install(
                new WindsorInstaller(),
                new RepositoryInstaller(),
                new ConsumerInstaller(),
                new BusInstaller());

            _bus = container.Resolve<IAdvancedBus>();
            var senderQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Sender");
            var senderExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Sender", ExchangeType.Fanout);
            _bus.Bind(senderExchange, senderQueue, string.Empty);

            var receiverQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Receiver");
            var receiverExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Receiver", ExchangeType.Fanout);
            _bus.Bind(receiverExchange, receiverQueue, string.Empty);

            _bus.Consume(senderQueue, q => q
                .Add<SendRequestToDataProviderCommand>(
                    (message, info) => new SenderConsumers<SendRequestToDataProviderCommand>(message, container))
                .Add<GetResponseFromDataProviderCommmand>(
                    (message, info) => new SenderConsumers<GetResponseFromDataProviderCommmand>(message, container))
                .Add<CreateTransactionCommand>(
                    (message, info) => new SenderConsumers<CreateTransactionCommand>(message, container))
                .Add<ReceiveEntryPointRequest>(
                    (message, info) => new SenderConsumers<ReceiveEntryPointRequest>(message, container))
                .Add<ReturnEntryPointResponse>(
                    (message, info) => new SenderConsumers<ReturnEntryPointResponse>(message, container))
                .Add<RaisingSecurityFlagCommand>(
                    (message, info) => new SenderConsumers<RaisingSecurityFlagCommand>(message, container))
                .Add<ConfiguringDataProviderCommand>(
                    (message, info) => new SenderConsumers<ConfiguringDataProviderCommand>(message, container))
                .Add<TransformingDataProviderResponseCommand>(
                    (message, info) => new SenderConsumers<TransformingDataProviderResponseCommand>(message, container))
                .Add<ErrorInDataProviderCommand>(
                    (message, info) => new SenderConsumers<ErrorInDataProviderCommand>(message, container))
                .Add<StartingCallCommand>(
                    (message, info) => new SenderConsumers<StartingCallCommand>(message, container))
                .Add<EndingCallCommand>((message, info) => new SenderConsumers<EndingCallCommand>(message, container)));

            _bus.Consume(receiverQueue, q => q
                .Add<RequestToDataProvider>(
                    (message, info) => new ReceiverConsumers<RequestToDataProvider>(message, container))
                .Add<EntryPointReceivedRequest>(
                    (message, info) => new ReceiverConsumers<EntryPointReceivedRequest>(message, container))
                .Add<ResponseFromDataProvider>(
                    (message, info) => new ReceiverConsumers<ResponseFromDataProvider>(message, container))
                .Add<EntryPointReturnedResponse>(
                    (message, info) => new ReceiverConsumers<EntryPointReturnedResponse>(message, container))
                .Add<BillTransactionMessage>(
                    (message, info) => new ReceiverConsumers<BillTransactionMessage>(message, container))
                .Add<SecurityFlagRaised>(
                    (message, info) => new ReceiverConsumers<SecurityFlagRaised>(message, container))
                .Add<DataProviderCallEnded>(
                    (message, info) => new ReceiverConsumers<DataProviderCallEnded>(message, container))
                .Add<DataProviderCallStarted>(
                    (message, info) => new ReceiverConsumers<DataProviderCallStarted>(message, container))
                .Add<DataProviderError>(
                    (message, info) => new ReceiverConsumers<DataProviderError>(message, container))
                .Add<DataProviderResponseTransformed>(
                    (message, info) => new ReceiverConsumers<DataProviderResponseTransformed>(message, container))
                .Add<DataProviderConfigured>(
                    (message, info) => new ReceiverConsumers<DataProviderConfigured>(message, container)));

            var apiReceiverQueue = _bus.QueueDeclare("DataPlatform.Api");
            var apiReceiverExchange = _bus.ExchangeDeclare("DataPlatform.Api", ExchangeType.Fanout);
            _bus.Bind(apiReceiverExchange, apiReceiverQueue, string.Empty);

            _bus.Consume(apiReceiverQueue,
                q => q.Add<RequestMetadataMessage>((message, info) => new ReceiverConsumers<RequestMetadataMessage>(message, container)));

            _log.DebugFormat("Data Provider Command Processor Service Started");
        }
 private IExchange DeclareVersionedExchanges(IAdvancedBus advancedBus, IConventions conventions, MessageVersionStack messageVersions, string exchangeType)
 {
     IExchange destinationExchange = null;
     while (!messageVersions.IsEmpty())
     {
         var messageType = messageVersions.Pop();
         var exchangeName = conventions.ExchangeNamingConvention(messageType);
         var sourceExchange = DeclareExchange(advancedBus, exchangeName, exchangeType);
         if (destinationExchange != null)
         {
             advancedBus.Bind(sourceExchange, destinationExchange, "#");
         }
         destinationExchange = sourceExchange;
     }
     return destinationExchange;
 }