代码段如下:
public static void main(String[] args) {
//kafka producer配置
Properties props = new Properties();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"IP:PORT");
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
//创建kafka Producer实例
String topicName = "topic_name";
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
//构建消息记录
ProducerRecord<String, String> record = new ProducerRecord<>(topicName,消息要写到哪个分区,"标记消息的key-是字符串格式", "消息体");
try {
//发送消息并获取记录
RecordMetadata metadata = producer.send(record).get();
//打印消息的时间戳和偏移量
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(metadata.timestamp()));
System.out.println("partition:"+metadata.partition());
System.out.println("时间:"+format);
System.out.println("偏移量:"+metadata.offset());
}catch (InterruptedException| ExecutionException e){
e.printStackTrace();
}finally {
//关闭Kafka Producer
producer.close();
}
}
打印的结果如下: