【问题标题】:Kafka Template - Not Applicable for the Arguments when using wildcardKafka 模板 - 使用通配符时不适用于参数
【发布时间】:2021-05-26 19:03:54
【问题描述】:

我一直在构建 Kafka Producer Service。我使用? 通配符类型的泛型作为键值,因此它可以是Integer String 等。

@Slf4j
public abstract class ProducerService<T> {

    protected KafkaClientConfigProperties properties;

    @Autowired
    protected KafkaTemplate<?, T> kafkaTemplate;

    public void send(T value, Iterable<Header> headers) {
        ProducerRecord<?, T> record = new ProducerRecord<>(properties.getTopic(), null, null, null, value, headers);
        this.kafkaTemplate.send(record);
    }

但是,在使用 ProducerRecord 参数调用 send 方法时,我遇到了一个错误

KafkaTemplate 类型中的方法 send(ProducerRecord) 不适用于参数 (ProducerRecord)

我也试过

ProducerRecord<String, T> record = new ProducerRecord<>(properties.getTopic(), null, null, null, value, headers);

并且有一个错误

ProducerRecord record = new ProducerRecord(properties.getTopic(), null, null, null, value, headers);

有人可以帮我理解代码有什么问题吗?谢谢

【问题讨论】:

  • 你能分享你实际扩展的代码然后使用抽象ProducerService吗?

标签: java generics apache-kafka producer-consumer


【解决方案1】:

这里有很多东西可以改变/修复。首先回答你提出的问题。您收到相关错误的原因是因为您正在创建的 ProducerRecord 包含 null 键变量。

由于这个类是泛型的,期望K作为键的类型,V作为值的类型,传入null意味着K的类型没有办法可以推断,这也是由于您将? 作为不正确的键类型这一事实而增加的。

有多种方法可以缓解这种情况。

  1. 如果您真的有兴趣通过headers 发送邮件,那么您的班级也应该接受密钥类型(而不是通配符)。考虑以下示例:
public abstract class ProducerService<K, T> {

    @Autowired
    protected KafkaTemplate<K, T> template;

    public void send(T value, Iterable<Header> headers) {
    ProducerRecord<K, T> record = new ProducerRecord<>("topic", null, null, null, value, headers);
    template.send(record);
    }

}
  1. 如果您对通过自定义标头发送不感兴趣,只需调用 KafkaTemplate#send 并传入要发送的对象就足够了:
public abstract class ProducerService<T> {

    @Autowired
    protected KafkaTemplate<String, T> template;

    public void send(T value, Iterable<Header> headers) {
    template.send("topic", value);
    }

}

正如您从上面的两个示例中看到的那样,键入正确的键类型而不使用通配符应该适合您。最后,还有一个建议应该是避免使类泛型。

对于特定的对象类型,不需要有多个生产者服务的实现。您可以简单地尝试概括您的方法,以便能够处理任何类型的值。

【讨论】:

  • 非常感谢!我现在明白了。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多