MassTransit 3.2.1 - Validation

我的梦境 提交于 2019-12-23 02:19:14

问题


I want to validate an incoming message, using FluentValidation in my case, and if it fails it should return immediately. I looked into http://docs.masstransit-project.com/en/latest/usage/observers.html, and in my case, I like the idea of

public class ConsumeObserver : IConsumeObserver
    {
    Task IConsumeObserver.PreConsume<T>(ConsumeContext<T> context)
    {
        //1.Validate here
        //2. If success go on to consumer
        //3. If fails exit with the result of validation and don't go through consumer.
    }

    Task IConsumeObserver.PostConsume<T>(ConsumeContext<T> context)
    {

    }

    Task IConsumeObserver.ConsumeFault<T>(ConsumeContext<T> context, Exception exception)
    {

    }
}

because I get the message already deserialized and so is easy to use the validator. The problem is that I don't know how to return without going through consumer and a the same time keep the validation errors.

Thank you.


回答1:


Observers typically watch versus take action, and that's the approach with observers in MassTransit. While you could throw an exception from the PreConsume method, which would cause the message to either retry or be sent to the error queue, it's not the most obvious behavior to developers down the road who may not understand why the message is failing.

Another approach would be to create middleware component that can validate the message, and if it's not valid, perform a specific action on the message (such as moving it to an invalid queue, or dumping it to a log, or whatever) so that the message is removed from the queue. It's important to understand how this might impact the message producer.

For instance, if it was a request message, and the sender is waiting on a response, discarding the message means that no response will be received. The default behavior of a consumer that throws an exception is to propagate the fault back to the requestor, completing the cycle, so keep that in mind.

Another option is to just add the validation behavior to the consumer, using either an injected validation interface, or within the consumer itself. That way, the handling of the message is close to the consumer which improves code cohesion and makes it easy to see what is happening.

Ideally, validating at the message producer is the best option, to avoid flooding the queue with invalid messages. So that's another option.

So, several choices, your requirements will dictate which makes the most sense.



来源:https://stackoverflow.com/questions/35867553/masstransit-3-2-1-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!