@KafkaListener @Payload Validation

从 2.2 版开始,现在可以更轻松地添加一个 Validator 来验证 @KafkaListener @Payload 参数。以前,你必须配置一个自定义 DefaultMessageHandlerMethodFactory 并将其添加到注册表中。现在,你可以将验证器添加到注册表本身。以下代码显示了如何执行此操作:

Starting with version 2.2, it is now easier to add a Validator to validate @KafkaListener @Payload arguments. Previously, you had to configure a custom DefaultMessageHandlerMethodFactory and add it to the registrar. Now, you can add the validator to the registrar itself. The following code shows how to do so:

@Configuration
@EnableKafka
public class Config implements KafkaListenerConfigurer {

    ...

    @Override
    public void configureKafkaListeners(KafkaListenerEndpointRegistrar registrar) {
      registrar.setValidator(new MyValidator());
    }

}

当您将 Spring Boot 与验证启动器一起使用时,它会自动配置一个 LocalValidatorFactoryBean,如下所示例:

When you use Spring Boot with the validation starter, a LocalValidatorFactoryBean is auto-configured, as the following example shows:

@Configuration
@EnableKafka
public class Config implements KafkaListenerConfigurer {

    @Autowired
    private LocalValidatorFactoryBean validator;
    ...

    @Override
    public void configureKafkaListeners(KafkaListenerEndpointRegistrar registrar) {
      registrar.setValidator(this.validator);
    }
}

以下示例显示了如何验证:

The following examples show how to validate:

public static class ValidatedClass {

  @Max(10)
  private int bar;

  public int getBar() {
    return this.bar;
  }

  public void setBar(int bar) {
    this.bar = bar;
  }

}
@KafkaListener(id="validated", topics = "annotated35", errorHandler = "validationErrorHandler",
      containerFactory = "kafkaJsonListenerContainerFactory")
public void validatedListener(@Payload @Valid ValidatedClass val) {
    ...
}

@Bean
public KafkaListenerErrorHandler validationErrorHandler() {
    return (m, e) -> {
        ...
    };
}

从第 2.5.11 版开始,对类级侦听器中 @KafkaHandler 方法的有返回值现在有效。请参阅 @KafkaListener on a Class

Starting with version 2.5.11, validation now works on payloads for @KafkaHandler methods in a class-level listener. See @KafkaListener on a Class.

从版本 3.1 开始,您可以转而执行一个 ErrorHandlingDeserializer 中的验证。详见 xref:kafka/serdes.adoc#error-handling-deserializer[Using ErrorHandlingDeserializer

Starting with version 3.1, you can perform validation in an ErrorHandlingDeserializer instead. See Using ErrorHandlingDeserializer for more information.