MassTransit Bus.Publish调用SendObserver

时间:2018-10-16 12:20:05

标签: masstransit

我注意到,当我调用Bus.Publish时,我的SendObserver与PublishObserver一起被调用。在我的原始方案中,我使用观察程序进行一些调试日志记录,在该日志记录中,我注意到当我调用Publish时,将使用同一消息调用PublishObserver和SendObserver。下面的示例代码重现了这种情况:

['d4', 'e5']

输出:

public class YourMessage { public string Text { get; set; } }

public class SendObserver : ISendObserver {
    public Task PreSend<T>(SendContext<T> context) where T : class
    {
        return Task.CompletedTask;
    }

    public Task PostSend<T>(SendContext<T> context) where T : class
    {
        Console.Out.WriteLineAsync($"Message Sent, Id: {context.MessageId}");

        return Task.CompletedTask;
    }

    public Task SendFault<T>(SendContext<T> context, Exception exception) where T : class
    {
        return Task.CompletedTask;
    }
}

public class PublishObserver : IPublishObserver
{
    public Task PrePublish<T>(PublishContext<T> context) where T : class
    {
        return Task.CompletedTask;
    }

    public Task PostPublish<T>(PublishContext<T> context) where T : class
    {
        Console.Out.WriteLineAsync($"Message Published, Id: {context.MessageId}");

        return Task.CompletedTask;
    }

    public Task PublishFault<T>(PublishContext<T> context, Exception exception) where T : class
    {
        return Task.CompletedTask;
    }
}
public class Program
{
    public static void Main()
    {
        var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
        {
            var host = sbc.Host(new Uri("rabbitmq://rabbitmq/PublishSendTest"), h =>
            {
                h.Username("guest");
                h.Password("guest");
            });

            sbc.ReceiveEndpoint(host, "test_queue", ep =>
            {
                ep.Handler<YourMessage>(context =>
                {
                    return Console.Out.WriteLineAsync($"Received: {context.Message.Text}");
                });
            });
        });

        bus.ConnectSendObserver(new SendObserver());
        bus.ConnectPublishObserver(new PublishObserver());

        bus.Start();

        bus.Publish(new YourMessage { Text = "Hi" });

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();

        bus.Stop();
    }
}

这是预期的行为吗?如果是这样,我该怎么做才能确定它是否是创建该消息的发布调用?

我使用的版本是5.1.5

1 个答案:

答案 0 :(得分:0)

不一致的观察者问题应在开发版本中解决,并已创建测试以验证支持的传输上的行为。释放后,仅应在实际的Send上调用发送观察者,而发布的观察者应仅在实际的Publish上调用。

感谢提出来,我不确定它是如何摆脱困境的。