KafkaProducerService.java 887 Bytes
package com.viontech.keliu.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.List;

@Service
@Slf4j
public class KafkaProducerService {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    public <V> ListenableFuture<SendResult<String, V>> sendMessage(String topic, V t){
        return kafkaTemplate.send(topic, t);
    }

    public <V> void sendMessages(String topic, List<V> list){
        if (!CollectionUtils.isEmpty(list)) {
            for (V v : list) {
                kafkaTemplate.send(topic, v);
            }
        }
    }
}