【问题标题】:Spring Boot Auto Configuration Failed Loading Spring Kafka PropertiesSpring Boot 自动配置加载 Spring Kafka 属性失败
【发布时间】:2018-03-10 16:57:35
【问题描述】:

Spring boot 无法加载属性。这是我通过 yaml 文件使用的属性。

 spring:
  kafka:
    bootstrap-servers: localhost:9092
    consumer:
      auto-commit-interval: 100
      enable-auto-commit: true
      group-id: ********************
      auto-offset-reset: earliest
      value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
    producer:
      batch-size: 16384
      buffer-memory: 33554432
      retries: 0
      value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
    listener:
      poll-timeout: 20000

我得到的例外是这个

原因:java.lang.IllegalAccessException:类 org.apache.kafka.common.utils.Utils 无法访问带有修饰符“protected”的类 org.springframework.kafka.support.serializer.JsonDeserializer 的成员

我认为构造函数是受保护的。请提供一种方法来实例化它。

【问题讨论】:

    标签: spring-boot spring-kafka


    【解决方案1】:

    没错。见:

    protected JsonDeserializer() {
            this((Class<T>) null);
        }
    
        protected JsonDeserializer(ObjectMapper objectMapper) {
            this(null, objectMapper);
        }
    
        public JsonDeserializer(Class<T> targetType) {
            this(targetType, new ObjectMapper());
            this.objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false);
            this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        }
    

    JsonDeserializer 并非设计为由默认构造函数实例化,因为它需要知道 targetType 才能反序列化。

    您可以将此类扩展到您的特定类型:

    public class FooJsonDeserializer extends JsonDeserializer<Foo> { }
    

    并已将其用作该 value-deserializer 属性的类值。

    或者你可以考虑自定义DefaultKafkaConsumerFactory

    @Bean
    public ConsumerFactory<?, ?> kafkaConsumerFactory(KafkaProperties properties) {
        Map<String, Object> consumerProperties = properties.buildConsumerProperties();
        consumerProperties.put(CommonClientConfigs.METRIC_REPORTER_CLASSES_CONFIG,
                MyConsumerMetricsReporter.class);
        DefaultKafkaConsumerFactory<Object, Object> consumerFactory =
              new DefaultKafkaConsumerFactory<>(consumerProperties);
        consumerFactory.setValueDeserializer(new JsonDeserializer<>(Foo.class));
        return consumerFactory;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      相关资源
      最近更新 更多