package tuyou.kafka.producer;
import java.util.Properties;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
/**
* 消息生产者
*
* @author:涂有
* @date 2017年6月1日 上午11:27:47
*/
public class MsgProducer extends Thread {
private final KafkaProducer<String, String> producer;
private final String topic;
private final boolean isAsync;
public MsgProducer(String topic, boolean isAsync) {
Properties properties = new Properties();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.142.129:9092");// broker
// 集群地址
properties.put(ProducerConfig.CLIENT_ID_CONFIG, "MsgProducer");// 自定义客户端id
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringSerializer");// key
// 序列号方式
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
"org.apache.kafka.common.serialization.StringSerializer");// value
// 序列号方式
// properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,CustomPartitioner.class.getCanonicalName());//自定义分区函数
// properties.load("properties配置文件");
this.producer = new KafkaProducer<String, String>(properties);
this.topic = topic;
this.isAsync = isAsync;
}
@Override
public void run() {
int msgNo = 0;
while (true) {
String msg = "Msg: " + msgNo;
String key = msgNo++ + "";
if (isAsync) {// 异步
producer.send(new ProducerRecord<String, String>(this.topic, key, msg),
new MsgProducerCallback(System.currentTimeMillis(), key, msg));
} else {// 同步
producer.send(new ProducerRecord<String, String>(this.topic, msg));
// producer.send(new ProducerRecord<String, String>(this.topic,
// key, msg));
}
System.out.println("发送:" + key + "-" + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 消息发送后的回调函数
*/
class MsgProducerCallback implements Callback {
private final long startTime;
private final String key;
private final String msg;
public MsgProducerCallback(long startTime, String key, String msg) {
this.startTime = startTime;
this.key = key;
this.msg = msg;
}
public void onCompletion(RecordMetadata recordMetadata, Exception e) {
long elapsedTime = System.currentTimeMillis() - startTime;
if (recordMetadata != null) {
System.out.println(msg + " be sended to partition no : " + recordMetadata.partition());
}
}
}
public static void main(String args[]) {
new MsgProducer("flume", false).start();// 开始发送消息
}
}
kafka-clients 0.10 消息生产者
最新推荐文章于 2024-08-08 18:53:24 发布