コード例 #1
0
ファイル: EventBusRabbitMQ.cs プロジェクト: Hansdas/Blog_New
 public void Subscribe <T, TH>()
     where T : EventData
     where TH : IEventHandler
 {
     _eventBusManager.AddSub <T, TH>();
     channel.QueueBind(queueName, exchangeName, typeof(T).Name);
 }
コード例 #2
0
        public void Subscribe <T, TH>()
            where T : EventData
            where TH : IEventHandler
        {
            _eventBusManager.AddSub <T, TH>();
            channel.QueueBind(queueName, exchangeName, typeof(T).Name);
            channel.QueueDeclare(queueName, true, false, false, null);
            var consumer = new EventingBasicConsumer(channel);

            consumer.Received += async(model, ea) =>
            {
                string eventName = ea.RoutingKey;
                byte[] resp      = ea.Body.ToArray();
                string body      = Encoding.UTF8.GetString(resp);
                _log.LogInformation(body);
                try
                {
                    Type eventType = _eventBusManager.FindEventType(eventName);
                    T    eventData = (T)JsonConvert.DeserializeObject(body, eventType);
                    IEventHandler <T> eventHandler = _eventBusManager.FindHandlerType(eventType) as IEventHandler <T>;
                    await eventHandler.Handler(eventData);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            };
            channel.BasicConsume(queueName, true, consumer);
        }