在春季启动Kafka中创建通用KafkaTemplate

时间:2020-07-16 06:25:35

标签: java spring spring-boot apache-kafka spring-kafka

我正在使用Spring Kafka来实现Kafka,这很酷。现在,我想创建一个通用的Kafka模板来发送消息。

类似这样的东西

        let btn = UIButton()
        btn.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(btn)
        
        btn.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -20).isActive = true
        btn.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -20).isActive = true
        btn.heightAnchor.constraint(equalToConstant: 50).isActive = true
        btn.widthAnchor.constraint(equalToConstant: 50).isActive = true

对于Kafka,键始终为String,但数据可能是不同的模型。

我收到错误信息

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

如果您将_template字段定义为泛型,则意味着_template只能发送相同的数据类型。U可以将_template`定义为

private final KafkaTemplate<String, Object> _template;

,然后添加一个新的私有泛型方法

private  <T> void send(String key ,T t){
    this._template.send(key, t);
}

全班定义:

public class ProductProducer implements IProductProducer{
    private final KafkaTemplate<String, Object> _template;

    public ProductProducer(KafkaTemplate<String, Object> _template) {
        this._template = _template;
    }

    @Override
    public ProductViewModel GetProduct(String id) {
        this.send(ProductTopicConstants.GET_PRODUCT, id);
        return new ProductViewModel("","",0,"");
    }

    @Override
    public void AddProduct(ProductViewModel product) {
        this.send(ProductTopicConstants.ADD_PRODUCT, product);
    }
    private  <T> void send(T t){
        this._template.send(ProductTopicConstants.GET_PRODUCT, id);
    }
}