代码之家  ›  专栏  ›  技术社区  ›  San Jaisy

在spring boot Kafka中创建通用KafkaTemplate

  •  0
  • San Jaisy  · 技术社区  · 6 年前

    我使用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,但数据可能是不同的模型。

    我得到的错误是

    enter image description here

    enter image description here

    0 回复  |  直到 6 年前
        1
  •  1
  •   neo    6 年前

    如果将字段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);
        }
    }