大众运输,返回消费消息

时间:2020-05-14 09:40:25

标签: .net rabbitmq masstransit

我是Masstransit的新手,我不确定如何配置它。 有没有办法将消耗的消息返回到我调用Consume方法的位置? Consume方法返回IBusControl,但无法保存该消息。

通过ReceiveEndpoint以某种方式调用实际的Consume方法,并且此Consume方法返回保存消息的Task任务。所以我的问题是,如何将此消息返回给ConsumeMessage方法,以便可以用结果填充InventoryItemObject。

public IInventory ConsumeMessage(string domainId)
    {
        using (consumer = new MassTransitConsumer(MassTransitConsumer.GetConfiguration()))
        {
            try
            {
                var message = consumer.Consume(domainId).StartAsync().Result;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        return new InventoryItemObject();
    }

        public IBusControl Consume(string queue)
    {

        var endpoint = new Uri(string.Concat(configuration.HostAddress, "/", queue));

        try
        {
            if (configuration.QueueType == "RabbitMQ" || string.IsNullOrEmpty(configuration.QueueType))
            {
                bus = Bus.Factory.CreateUsingRabbitMq(rabbit =>
                {
                    IRabbitMqHost host = rabbit.Host(configuration.HostAddress, settings =>
                    {
                        settings.Username(configuration.Username);
                        settings.Password(configuration.Password);
                    });

                    rabbit.ReceiveEndpoint(host, queue, c =>
                    {
                        c.UseConcurrencyLimit(1);
                        c.UseRetry(retryConfig => retryConfig.Incremental(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)));
                        c.Consumer(() => new InventoryConsumer(_connectionString));
                    });
                });

                bus.Start();
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(ex.Message);
        }

        return bus;
    }

public Task Consume(ConsumeContext<IInventory> context)
    {
        var inventory = context.Message;

        _logger.LogDebug($"Order object: {JsonConvert.SerializeObject(inventory, Formatting.Indented)}");
        _logger.LogDebug("Stating timer for UserChangeEventConsumer:");

        var timer = new Stopwatch();
        timer.Start();

        var message = context.Message;

        SetMessageAsConsumed(message);

        timer.Stop();
        _logger.LogDebug($"UserChangeEventConsumer completed in {timer.Elapsed.TotalSeconds} seconds.");

        return Task.FromResult(message);
    }

1 个答案:

答案 0 :(得分:0)

您是否有特定原因想要返回此消息?据我所知,最佳做法是不让Consume方法返回消息,因为那里不应该有人收听。

如果您想将某些东西退还给发布者,则应使用request/response pattern