我在应用中间件登录masstransit时遇到了问题。我想记录发布到总线上的每条消息。所以我遵循我在这里找到的这些步骤:http://masstransit-project.com/MassTransit/advanced/middleware/custom.html,然后我用下面这样的东西结束:
public static class MassTransitLoggerExtenions
{
public static void UseLogger<T>(this IPipeConfigurator<T> configurator,ILoggingBusControl loggingBusControl)
where T : class, PipeContext
{
configurator.AddPipeSpecification(new ExceptionLoggerSpecification<T>(loggingBusControl));
}
}
public class ExceptionLoggerSpecification<T> :
IPipeSpecification<T>
where T : class, PipeContext
{
private readonly ILoggingBusControl loggingBusControl;
public ExceptionLoggerSpecification(ILoggingBusControl loggingBusControl)
{
this.loggingBusControl = loggingBusControl;
}
public IEnumerable<ValidationResult> Validate()
{
return Enumerable.Empty<ValidationResult>();
}
public void Apply(IPipeBuilder<T> builder)
{
builder.AddFilter(new ExceptionLoggerFilter<T>(loggingBusControl));
}
}
public class ExceptionLoggerFilter<T> : IFilter<T> where T : class, PipeContext
{
private readonly ILoggingBusControl loggingBusControl;
public ExceptionLoggerFilter(ILoggingBusControl loggingBusControl)
{
this.loggingBusControl = loggingBusControl;
}
public void Probe(ProbeContext context)
{
}
public async Task Send(T context, IPipe<T> next)
{
throw new Exception("Foo");
try
{
await next.Send(context);
}
catch (Exception ex)
{
}
}
}
这是我对IBusControl
的简单抽象
public class LoggingBusControl : ILoggingBusControl
{
private readonly IBusControl busControl;
public LoggingBusControl()
{
busControl = GetBusControl();
busControl.Start();
}
private static IBusControl GetBusControl()
{
var busControl = Bus.Factory.CreateUsingRabbitMq(x =>
{
var host = x.Host(new Uri("rabbitmq://localhost/#/queues/%2F/logging_queue"), h =>
{
h.Username("guest");
h.Password("guest");
});
});
return busControl;
}
public void Log<T>(T log) where T : ILog
{
busControl.Publish<ILog>(log);
}
}
用法
builder.Register(context =>
{
var busControl = Bus.Factory.CreateUsingRabbitMq(rabbitMqConfig =>
{
var host = rabbitMqConfig.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h =>
{
h.Username("guest");
h.Password("guest");
});
var logger = context.Resolve<ILoggingBusControl>();
rabbitMqConfig.UseLogger(logger);
});
return busControl;
})
.SingleInstance()
.As<IBusControl>()
.As<IBus>()
.OnActivated(args => args.Instance.Start());
然后我将IBusControl注入到控制器构造函数中
public OrderController(IOrderService orderService,IBusControl busControl)
{
this.orderService = orderService;
this.busControl = busControl;
}
消息被正确发布,ExceptionLoggerFilter
、ExceptionLoggerSpecification
构造函数被调用,但ExceptionLoggerFilter
中的方法Probe
和Send
从未被调用。我做错了什么?
发布于 2018-04-13 01:19:31
您没有指定是否尝试将中间件用于正在发送的消息和正在消费的消息,但从您的问题看,您似乎正在尝试将其用于正在发送的消息。
如果是这种情况(或遇到同样问题的任何人),请注意,the Mass Transit documentation中描述的中间件只适用于正在使用的消息,而不适用于正在发送的消息。
对于日志消息,尤其是发送的消息,你最好使用the Mass Transit audit feature,就像@Alexey Zimarev在他的评论中提到的那样。
https://stackoverflow.com/questions/45545846
复制相似问题