【问题标题】:Creating generic KafkaTemplate in spring boot Kafka在 Spring Boot Kafka 中创建通用 KafkaTemplate
【发布时间】:2020-07-16 06:25:35
【问题描述】:

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

类似的东西

    public class ProductProducer<T> implements IProductProducer{
        private final KafkaTemplate<String, T> _template;
    
        public ProductProducer(KafkaTemplate<String, T> _template) {
            this._template = _template;
        }
    
        @Override
        public ProductViewModel GetProduct(String id) {
            this._template.send(ProductTopicConstants.GET_PRODUCT, id);
            return new ProductViewModel("","",0,"");
        } 

       @Override
        public void AddProduct(ProductViewModel product) {
           this._template.send(ProductTopicConstants.ADD_PRODUCT, product);
        }

    }

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

我得到的错误是

【问题讨论】:

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


    【解决方案1】:

    如果你将_template字段定义为generic,则表示_template只能发送相同的数据类型。你可以将_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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 1970-01-01
      • 2019-11-27
      • 2022-08-18
      • 1970-01-01
      相关资源
      最近更新 更多