Exemplo n.º 1
0
        public async Task PublishAsync <TEvent>(TEvent @event, EventMetadata metadata) where TEvent : IDomainEvent
        {
            var envelope = new MessageEnvelope(@event, metadata);
            var topic    = Convention.TopicName(_config.BoundedContext, @event.GetType().Name);

            var res = await _producer.ProduceAsync(topic, null, envelope);

            if (res.Error.HasError)
            {
                throw new PublishingException(res.Error.Reason);
            }
        }
Exemplo n.º 2
0
        public async Task StartConsumer(IEnumerable <Subscription> subscriptions)
        {
            _subscriptions = new HashSet <Subscription>(subscriptions);
            var topics = _subscriptions.Select(x => Convention.TopicName(x.BoundedContext, x.EventName));

            _consumer.Assign(topics.Select(x => new TopicPartition(x, 0)));
            _consumer.Subscribe(topics);

            _isConsuming = true;

            while (_isConsuming)
            {
                var exist = _consumer.Consume(out var msg, _defaultTimeout);

                if (!exist)
                {
                    continue;
                }

                await HandleMessage(msg);
            }
        }
Exemplo n.º 3
0
        private async Task HandleMessage(Message <Ignore, MessageEnvelope> msg)
        {
            var subscription = _subscriptions.SingleOrDefault(x =>
                                                              string.Equals(Convention.TopicName(x.BoundedContext, x.EventName), msg.Topic));

            if (subscription == null)
            {
                throw new ConsumingException("Unexpected message consumed: No subscription registered");
            }

            var @event = ((JObject)msg.Value.Payload).ToObject(subscription.EventType);

            var factory = typeof(IEventHandlerFactory)
                          .GetMethod(nameof(IEventHandlerFactory.GetEventHandler))
                          .MakeGenericMethod(subscription.EventType);
            var handler = factory.Invoke(_eventHandlerFactory, null);

            var handle = typeof(IEventHandler <>)
                         .MakeGenericType(subscription.EventType)
                         .GetMethod("Handle");

            await(Task) handle.Invoke(handler, new[] { @event });
        }