java向kafka批量均勻傳送資料的方法
阿新 • • 發佈:2019-01-01
RT。
import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import java.io.Serializable; import java.util.List; import java.util.Properties; /** * Created by dell on 2018/6/18. */ public class NewKafkaSendUtil implements Serializable{ public static voidsendMsg(String brokerList,String topic,List<String> datas){ Properties properties = new Properties(); properties.put("bootstrap.servers",brokerList); properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer"); properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer"); KafkaProducer producer = null; try{ producer = new KafkaProducer(properties); for(int i=0;i<datas.size();i++){ ProducerRecord<String,String> message = new ProducerRecord<String, String>(topic,datas.get(i)); producer.send(message); } }catch(Exception ex){ ex.printStackTrace(); }finally{ if(producer != null){ producer.close(); } } } }