简体   繁体   English

Spring - 在 RabbitMQ 侦听器中验证传入消息

[英]Spring - Validate incoming message in RabbitMQ listener

I am using Spring Boot framework.我正在使用 Spring Boot 框架。 I want to send an object from a service to another service via RabbitMQ like this:我想通过 RabbitMQ 将一个对象从一个服务发送到另一个服务,如下所示:

Service A:服务一:

rabbitTemplate.convertAndSend("queue", createAccountRequestMessage);

Service B:服务乙:

@RabbitListener(queues = "queue")
public void onAccountRequested(@Valid CreateAccountRequestMessage createAccountRequestMessage, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG, long tag) throws IOException
{
    
}

In CreateAccountRequestMessage class I have defined some validation annotations like @NotEmpty , @NotNull and etc, but when I'm sending wrong message from service A to service B, @Valid annotation doesn't work and CreateAccountRequestMessage object is not validated before invoke onAccountRequested method.CreateAccountRequestMessage类中,我定义了一些验证注释,如@NotEmpty@NotNull等,但是当我从服务 A 向服务 B 发送错误消息时,@ @Valid注释不起作用并且CreateAccountRequestMessage对象在调用onAccountRequested方法之前未验证.

You need to set the validator in DefaultMessageHandlerMethodFactory .您需要在DefaultMessageHandlerMethodFactory设置验证器。

@Autowired
SmartValidator validator;

@Bean
public DefaultMessageHandlerMethodFactory messageHandlerMethodFactory() {
    DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
    factory.setValidator(this.validator);
    return factory;
}

Then you also need to specify the @Payload annotation along with the @Valid annotation.然后您还需要指定@Payload注释和@Valid注释。

@RabbitListener(queues = "queue")
public void onAccountRequested(@Valid @Payload CreateAccountRequestMessage 
    createAccountRequestMessage, Channel channel, 
    @Header(AmqpHeaders.DELIVERY_TAG, long tag) throws IOException
{

}

Now MethodArgumentNotValidException will be thrown and the message will be discarded, or you can send the message to a dead letter exchange.现在将抛出MethodArgumentNotValidException并丢弃消息,或者您可以将消息发送到死信交换。

I had the same problem.我有同样的问题。 The answer of @Praveer works well except SmartValidator.除了 SmartValidator,@Praveer 的答案效果很好。 I post here my solution, which is inspired by this article https://blog.trifork.com/2016/02/29/spring-amqp-payload-validation/我在这里发布了我的解决方案,它的灵感来自这篇文章https://blog.trifork.com/2016/02/29/spring-amqp-payload-validation/

@Configuration
@EnableRabbit
@Slf4j
public class CmsMQConfig implements RabbitListenerConfigurer {

    @Value("${dw.rabbitmq.hosts}")
    private String hosts;

    @Value("${dw.rabbitmq.username}")
    private String username;

    @Value("${dw.rabbitmq.password}")
    private String password;

    @Value("${dw.rabbitmq.virtual-host}")
    private String virtualHost;

    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory());
        factory.setMessageConverter(messageConverter());
        return factory;
    }

    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(hosts);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        return connectionFactory;
    }

    @Bean
    public Jackson2JsonMessageConverter messageConverter() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JodaModule());
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return new Jackson2JsonMessageConverter(mapper);
    }

    @Bean
    public DefaultMessageHandlerMethodFactory defaultHandlerMethodFactory() {
        DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
        factory.setValidator(amqpValidator());
        return factory;
    }

    @Bean
    public Validator amqpValidator() {
        return new OptionalValidatorFactoryBean();
    }

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
        registrar.setContainerFactory(rabbitListenerContainerFactory());
        registrar.setMessageHandlerMethodFactory(defaultHandlerMethodFactory());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM