kafka中生产者示例代码:
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
import java.util.concurrent.Future;
public class Producer {
public static final String brokerList = "10.201.83.207:9092,10.202.82.49:9092,10.202.43.113:9092";
public static final String topic = "test-001";
public static Properties initConfig() {
Properties properties = new Properties();
properties.setProperty(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList);
properties.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.setProperty(ProducerConfig.CLIENT_ID_CONFIG, "test-001");
//可重试异常,配置retries参数后再可重试的次数内发送成功不会抛出异常
properties.setProperty(ProducerConfig.RETRIES_CONFIG,"10");
return properties;
}
public static void sendWithCallback(Properties props )throws Exception{
KafkaProducer<String, String> producer = new KafkaProducer(props);
ProducerRecord<String, String> record = new ProducerRecord<>(topic, "hello world");
producer.send(record, new Callback() {
@Override
public void onCompletion(RecordMetadata metadata, Exception e) {
if(e != null){
System.out.println("send failed and error msg is "+e.getMessage());
}else {
System.out.println("callback send success , topic="+metadata.topic()+" , partition="+metadata.partition());
}
}
});
}
public static void sendWithFuture(Properties props)throws Exception{
KafkaProducer<String, String> producer = new KafkaProducer(props);
ProducerRecord<String, String> record = new ProducerRecord<>(topic, "hello world");
Future<RecordMetadata> future = producer.send(record);
RecordMetadata metadata = future.get();
System.out.println("future send success , topic="+metadata.topic()+" , partition="+metadata.partition());
}
public static void main(String[] args) throws Exception {
Properties props = initConfig();
sendWithCallback(props);
sendWithFuture(props);
Thread.sleep(100000);
}