コード例 #1
0
        public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var subAlreadyExists = _handlers.FirstOrDefault(x => x.Handler == handler);

            if (subAlreadyExists == null)
            {
                if (!_persistentConnection.IsConnected)
                {
                    _policy.Execute(context => _persistentConnection.TryConnect(), new Dictionary <string, object>
                    {
                        {
                            "logmessage",
                            "RabbitMQ Client could not connect "
                        }
                    });
                }

                using (var channel = _persistentConnection.CreateModel())
                {
                    var eventName = typeof(T).FullName;

                    _handlers.Add(new HandlerSubscription(handler, typeof(T), eventName));

                    channel.QueueBind(_queueName,
                                      _exchangeName,
                                      eventName);
                    StartBasicConsume();
                }
            }
        }
コード例 #2
0
        public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName))
            {
                _handlers[eventName].Add(handler);
            }
            else
            {
                if (!_persisterConnection.IsConnected)
                {
                    _persisterConnection.TryConnect();
                }

                using (var channel = _persisterConnection.CreateModel())
                {
                    channel.QueueBind(queue: _queueName,
                                      exchange: BROKER_NAME,
                                      routingKey: eventName);

                    _handlers.Add(eventName, new List <IIntegrationEventHandler>());
                    _handlers[eventName].Add(handler);
                    _eventTypes.Add(typeof(T));
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// 摘要:
        ///     表示一个取消订阅事件的方法
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="handler">事件处理</param>
        public void Unsubscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName) && _handlers[eventName].Contains(handler))
            {                                         //如果该事件类型存在事件处理
                _handlers[eventName].Remove(handler); //移除事件处理

                if (_handlers[eventName].Count == 0)  //如果该事件类型不存在其他的事件处理
                {
                    _handlers.Remove(eventName);      //从事件处理字典中移除事件类型
                    var eventType = _eventTypes.Single(e => e.Name == eventName);
                    _eventTypes.Remove(eventType);    //从时间类型列表中移除事件类型。
                    _model.QueueUnbind(queue: _queueName,
                                       exchange: _brokerName,
                                       routingKey: eventName);//与交换机解除绑定。

                    if (_handlers.Keys.Count == 0)
                    {
                        _queueName = string.Empty;
                        _model.Dispose();
                        _connection.Dispose();
                    }
                }
            }
        }
コード例 #4
0
        public async Task CallHandlerAsync <TRequest, TResponse, TIntegrationEventHandler>(ILifetimeScope scope,
                                                                                           QueueOptions options) where TRequest : IntegrationEvent
            where TResponse : IntegrationEvent
        {
            EventingBasicConsumer consumer = BuildChannel(options);

            consumer.Received += async(model, args) =>
            {
                TRequest request = null;

                using (ILifetimeScope innerScope = scope.BeginLifetimeScope())
                    using (MessageSerializer serializaer = new MessageSerializer())
                        using (IIntegrationEventHandler <TRequest, TResponse> handler = innerScope.Resolve <IIntegrationEventHandler <TRequest, TResponse> >())
                        {
                            IBasicProperties props      = args.BasicProperties;
                            IBasicProperties replyProps = Channel.CreateBasicProperties();
                            replyProps.CorrelationId = props.CorrelationId;

                            request = Activator.CreateInstance <TRequest>();

                            if (args.Body.Length > 0)
                            {
                                request = serializaer.Deserialize <TRequest>(args.Body.ToArray())[0];
                            }

                            TResponse response = await handler.Handle(request);

                            Channel.BasicPublish("", props.ReplyTo, replyProps, serializaer.Serialize(response)[0]);
                            Channel.BasicAck(args.DeliveryTag, false);
                        }
            };
        }
コード例 #5
0
        public void Unsubscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (!_handlers.ContainsKey(eventName) || !_handlers[eventName].Contains(handler))
            {
                return;
            }

            _handlers[eventName].Remove(handler);

            if (_handlers[eventName].Count != 0)
            {
                return;
            }

            _handlers.Remove(eventName);

            var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName);

            if (eventType != null)
            {
                _eventTypes.Remove(eventType);
            }
        }
コード例 #6
0
        public void Unsubscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEventBase
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName) && _handlers[eventName].Contains(handler))
            {
                _handlers[eventName].Remove(handler);

                if (_handlers[eventName].Count == 0)
                {
                    _handlers.Remove(eventName);
                    var eventType = _eventTypes.Single(e => e.Name == eventName);
                    _eventTypes.Remove(eventType);
                    _connection.Item1.QueueUnbind(queue: _queueName,
                                                  exchange: _brokerName,
                                                  routingKey: eventName);

                    if (_handlers.Keys.Count == 0)
                    {
                        _queueName = string.Empty;
                        _connection.Item1.Close();
                        _connection.Item2.Close();
                    }
                }
            }
        }
コード例 #7
0
 public DataSensorsHandlerWrapper(IIntegrationEventHandler <DataSensorsAddedIntegrationEvent <DataSensorsAddedContent> > dataHandler,
                                  INotice notice,
                                  ILogger <DataSensorsHandlerWrapper> logger)
 {
     _dataHandler = dataHandler;
     _notice      = notice;
     _logger      = logger;
 }
        public void RemoveSubscription <T>(IIntegrationEventHandler <T> integrationEventHandler)
            where T : IntegrationEvent
        {
            var eventName       = GetEventKey <T>();
            var handlerToRemove = DoFindSubscriptionToRemove(eventName, integrationEventHandler.GetType());

            DoRemoveHandler(eventName, handlerToRemove);
        }
コード例 #9
0
 public UserCreationCompletedIntegrationEventHandlerTest()
 {
     _accountGetterServiceMock = new Mock <IAccountGetterService>();
     _accountConfirmationRequestServiceMock = new Mock <IAccountConfirmationRequestService>();
     _integrationEventBusMock = new Mock <IIntegrationEventBus>();
     _loggerMock = new Mock <ILogger>();
     _userCreatedIntegrationEventHandler = new UserCreationCompletedIntegrationEventHandler(_accountGetterServiceMock.Object,
                                                                                            _accountConfirmationRequestServiceMock.Object, _integrationEventBusMock.Object, _loggerMock.Object);
 }
コード例 #10
0
 public UserCreationCompletedIntegrationEventFailureHandlerTest()
 {
     _accountGetterServiceMock          = new Mock <IAccountGetterService>();
     _accountDataConsistencyServiceMock = new Mock <IAccountDataConsistencyService>();
     _integrationEventBusMock           = new Mock <IIntegrationEventBus>();
     _loggerMock = new Mock <ILogger>();
     _userCreatedIntegrationEventHandlerFailure = new UserCreationCompletedIntegrationEventFailureHandler(_accountGetterServiceMock.Object,
                                                                                                          _accountDataConsistencyServiceMock.Object, _integrationEventBusMock.Object, _loggerMock.Object);
 }
コード例 #11
0
 public BackgroundTasks(ILogger <BackgroundTasks> logger, IEventBus eventBus, TelemetryClient telemetryClient, IOptions <TopicsConfiguration> topicsConfiguration,
                        IIntegrationEventHandler <OriginalImageUploadedIntegrationEvent> imageUploadedEventHandler, IIntegrationEventHandler <ImageDeletedIntegrationEvent> imageDeletedEventHandler)
 {
     _logger                    = logger;
     _eventBus                  = eventBus;
     _telemetryClient           = telemetryClient;
     _topicsConfiguration       = topicsConfiguration;
     _imageUploadedEventHandler = imageUploadedEventHandler;
     _imageDeletedEventHandler  = imageDeletedEventHandler;
 }
コード例 #12
0
 public UserDeletionCompletedIntegrationEventFailureHandlerTest()
 {
     _loggerMock = new Mock <ILogger>();
     _integrationEventBusMock = new Mock <IIntegrationEventBus>();
     _domainEventStoreMock    = new Mock <IDomainEventStore>();
     _accountRepositoryMock   = new Mock <IAccountRepository>();
     _userDeletionCompletedIntegrationEventFailure = new UserDeletionCompletedIntegrationEventFailureHandler(
         _loggerMock.Object, _integrationEventBusMock.Object, _domainEventStoreMock.Object,
         _accountRepositoryMock.Object);
 }
コード例 #13
0
        public void Subscribe <T>(IIntegrationEventHandler <T> eventHandler) where T : IntegrationEvent
        {
            string exchangeName = "";
            string queueName    = "";

            if (typeof(T) == typeof(UserCreatedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameAdd;
                queueName    = EventBusInfo.queueNameAdd;
            }
            else
            if (typeof(T) == typeof(UserEditedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameEdit;
                queueName    = EventBusInfo.queueNameEdit;
            }
            else
            if (typeof(T) == typeof(UserRemovedIntegrationEvent))
            {
                exchangeName = EventBusInfo.topicExchangeNameDelete;
                queueName    = EventBusInfo.queueNameDelete;
            }

            _channel.ExchangeDeclare(
                exchange: exchangeName,
                type: "fanout",
                durable: true
                );
            _channel.QueueDeclare(queue: queueName,
                                  durable: true,
                                  exclusive: false,
                                  autoDelete: false,
                                  arguments: null);
            _channel.QueueBind(
                queue: queueName,
                exchange: exchangeName,
                routingKey: ""
                );
            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += async(model, args) =>
            {
                try
                {
                    string message = Encoding.UTF8.GetString(args.Body);
                    var    @event  = JsonConvert.DeserializeObject <T>(message);
                    await eventHandler.Handle(@event);
                }
                catch (Exception) { }
            };
            _channel.BasicConsume(queue: queueName,
                                  autoAck: true,
                                  consumer: consumer);
        }
コード例 #14
0
        public ChallengeStartingEventHandlerTests()
        {
            _mathChallengeServiceMock = new Mock <IMathChallengeService>();
            _quizServiceMock          = new Mock <IQuizService>();
            _eventBusMock             = new Mock <IEventBus>();
            var loggerMock = new Mock <ILogger <ChallengeStartingEventHandler> >();

            _handler = new ChallengeStartingEventHandler(
                _mathChallengeServiceMock.Object,
                _quizServiceMock.Object,
                _eventBusMock.Object,
                loggerMock.Object
                );
        }
コード例 #15
0
        ///<inheritdoc/>
        public virtual void Subscribe(IIntegrationEventHandler handler, string topic = null)
        {
            var topicName = topic ?? handler.Topic;

            if (!Topics.ContainsKey(topicName))
            {
                Topics.Add(topicName, new List <IIntegrationEventHandler> {
                    handler
                });
            }
            else if (Topics[topicName] != handler)
            {
                Topics[topicName].Add(handler);
            }
        }
コード例 #16
0
        public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName))
            {
                _handlers[eventName].Add(handler);
            }
            else
            {
                var channel = GetChannel();
                channel.QueueBind(_queueName, _brokerName, eventName);
                _handlers.Add(eventName, new List <IIntegrationEventHandler>());
                _handlers[eventName].Add(handler);
                _eventTypes.Add(typeof(T));
            }
        }
コード例 #17
0
        public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName))
            {
                _handlers[eventName].Add(handler);
            }
            else
            {
                _handlers.Add(eventName, new List <IIntegrationEventHandler>());

                _handlers[eventName].Add(handler);

                _eventTypes.Add(typeof(T));
            }
        }
コード例 #18
0
 public void SubscribeDynamic(string eventName, IIntegrationEventHandler <dynamic> handler)
 {
     try
     {
         this.OnMessageReceived += (async(msg, topic) =>
         {
             if (topic.Equals(eventName))
             {
                 await handler.Handle(msg);
             }
         });
         this.DoInternalSubscription(eventName);
         this.memory.AddDynamicSubscription(eventName, handler);
     }
     catch (NMSException ex)
     {
         throw new NMSException("Could not subscribe dynamically ", ex);
     }
 }
コード例 #19
0
        public async Task SubscribeAsync <TRequestEvent, TIntegrationEventHandler>(ILifetimeScope scope,
                                                                                   QueueOptions options = null) where TRequestEvent : IntegrationEvent
            where TIntegrationEventHandler : IIntegrationEventHandler <TRequestEvent>
        {
            Tuple <string, EventingBasicConsumer> channelData = BuildChannel(options);

            channelData.Item2.Received += async(model, args) =>
            {
                using (ILifetimeScope innerScope = scope.BeginLifetimeScope())
                    using (MessageSerializer serializaer = new MessageSerializer())
                        using (IIntegrationEventHandler <TRequestEvent> handler = innerScope.Resolve <IIntegrationEventHandler <TRequestEvent> >())
                        {
                            TRequestEvent request = serializaer.Deserialize <TRequestEvent>(args.Body.ToArray())[0];
                            await handler.Handle(request);
                        }
            };

            Channel.BasicConsume(channelData.Item1, true, channelData.Item2);
        }
コード例 #20
0
        /// <summary>
        /// 摘要:
        ///     表示一个订阅事件的方法
        /// </summary>
        /// <typeparam name="T">事件类型</typeparam>
        /// <param name="handler">事件处理</param>
        public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName))
            {
                _handlers[eventName].Add(handler);
            }
            else
            {
                var channel = GetChannel();
                channel.QueueBind(queue: _queueName,
                                  exchange: _brokerName,
                                  routingKey: eventName);//从交换机根据事件类型获取消息。
                //记录事件处理
                _handlers.Add(eventName, new List <IIntegrationEventHandler>());
                _handlers[eventName].Add(handler);
                _eventTypes.Add(typeof(T));//记录事件类型
            }
        }
コード例 #21
0
 public void Subscribe <T>(string eventName, IIntegrationEventHandler <T> integrationEventHandler)
     where T : IntegrationEvent
 {
     try
     {
         this.OnMessageReceived += (async(msg, topic) =>
         {
             if (topic.Equals(eventName) || topic.Equals("topic://" + eventName))
             {
                 await integrationEventHandler.Handle((T)msg);
             }
         });
         this.DoInternalSubscription(eventName);
         this.memory.AddSubscription <T>(eventName, integrationEventHandler);
     }
     catch (EventBusException ex)
     {
         throw new EventBusException("Could not subscribe ", ex);
     }
 }
コード例 #22
0
        public void Subscribe <T>(IIntegrationEventHandler <T> handler)
            where T : IntegrationEvent
        {
            var eventType = typeof(T).FullName;

            if (eventType != null)
            {
                if (_handlersDictionary.ContainsKey(eventType))
                {
                    var handlers = _handlersDictionary[eventType];
                    handlers.Add(handler);
                }
                else
                {
                    _handlersDictionary.Add(eventType, new List <IIntegrationEventHandler> {
                        handler
                    });
                }
            }
        }
コード例 #23
0
        public void Unsubscribe(IIntegrationEventHandler handler)
        {
            var eventType = handler.GetType().BaseType.GetGenericArguments().First();

            if (_handlers.ContainsKey(eventType))
            {
                _handlers.Remove(eventType);
                if (!_persistentConnection.IsConnected)
                {
                    _policy.Execute((context) => _persistentConnection.TryConnect(), new Dictionary <string, object>()
                    {
                        {
                            "logmessage",
                            "RabbitMQ Client could not connect "
                        }
                    });
                }
                _persistentConnection.CreateChannel();
                _persistentConnection.RemoveRoutingKey(eventType.Name);
            }
        }
コード例 #24
0
        public void Unsubscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName) && _handlers[eventName].Contains(handler))
            {
                _handlers[eventName].Remove(handler);

                if (_handlers[eventName].Count == 0)
                {
                    _handlers.Remove(eventName);

                    var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName);

                    if (eventType != null)
                    {
                        _eventTypes.Remove(eventType);

                        if (!_persisterConnection.IsConnected)
                        {
                            _persisterConnection.TryConnect();
                        }

                        using (var channel = _persisterConnection.CreateModel())
                        {
                            channel.QueueUnbind(queue: _queueName,
                                                exchange: BROKER_NAME,
                                                routingKey: eventName);

                            if (_handlers.Keys.Count == 0)
                            {
                                _queueName = string.Empty;

                                _consumerChannel.Close();
                            }
                        }
                    }
                }
            }
        }
コード例 #25
0
        public async Task Subscribe <T>(string topicName, string subscriptionName, IIntegrationEventHandler <T> handler, int maxConcurrentCalls = 1)
            where T : IntegrationEvent
        {
            if (subscriptionName == null)
            {
                throw new ArgumentNullException(nameof(subscriptionName));
            }

            string key = GetSubscriptionKey(topicName, subscriptionName);

            if (_subscriptions.ContainsKey(key))
            {
                throw new ArgumentException($"Subscription {subscriptionName} for topic {topicName} already exist");
            }

            await _serviceBusPersistentConnection.CreateSubscriptionIfNotExists(topicName, subscriptionName);

            var client = new SubscriptionClient(_serviceBusPersistentConnection.ConnectionString, topicName, subscriptionName);

            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = maxConcurrentCalls,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };

            client.RegisterMessageHandler(async(message, token) =>
            {
                var model = JsonConvert.DeserializeObject <T>(Encoding.UTF8.GetString(message.Body));
                await handler.Handle(model);

                await client.CompleteAsync(message.SystemProperties.LockToken);
            }, messageHandlerOptions);

            _subscriptions.TryAdd(key, 0);
        }
コード例 #26
0
        public void Subscribe <TEvent>(IIntegrationEventHandler <TEvent> handler) where TEvent : IntegrationEvent
        {
            string handlerName = handler.GetType().Name;
            string eventName   = typeof(TEvent).FullName;


            _logger.Information("Handler {HandlerName} is subscribing to event {EventName}",
                                handlerName, eventName);

            RenewConnectionIfNeeded();

            using (var channel = _rabbitMqPersistentConnection.CreateModel())
            {
                channel.QueueBind(queue: _queueName ?? string.Empty,
                                  exchange: ExchangeName,
                                  routingKey: eventName,
                                  arguments: null);
            }

            InMemoryEventBus.Instance.Subscribe(handler);

            StartBasicConsume();
        }
コード例 #27
0
        public void Unsubscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
        {
            var eventName = typeof(T).Name;

            if (_handlers.ContainsKey(eventName) && _handlers[eventName].Contains(handler))
            {
                _handlers[eventName].Remove(handler);

                if (_handlers[eventName].Count == 0)
                {
                    _handlers.Remove(eventName);
                    var eventType = _eventTypes.Single(e => e.Name == eventName);
                    _eventTypes.Remove(eventType);
                    _model.QueueUnbind(_queueName, _brokerName, eventName);

                    if (_handlers.Keys.Count == 0)
                    {
                        _queueName = String.Empty;
                        _model.Dispose();
                        _connection.Dispose();
                    }
                }
            }
        }
コード例 #28
0
ファイル: InMemoryEventBus.cs プロジェクト: imgen/TopAct
 public HandlerSubscription(IIntegrationEventHandler handler, string eventName)
 {
     Handler   = handler;
     EventName = eventName;
 }
コード例 #29
0
ファイル: InMemoryEventBus.cs プロジェクト: imgen/TopAct
 public void Subscribe <T>(IIntegrationEventHandler <T> handler)
     where T : IntegrationEvent
 {
     _handlers.Add(new HandlerSubscription(handler, typeof(T).FullName));
 }
コード例 #30
0
 public void Subscribe <T>(IIntegrationEventHandler <T> handler) where T : IntegrationEvent
 {
     InMemoryEventBus.Instance.Subscribe(handler);
 }