4 changed files with 82 additions and 1 deletions
@ -0,0 +1,55 @@ |
|||
package com.zc.business.message.device.subscribe; |
|||
|
|||
import lombok.extern.slf4j.Slf4j; |
|||
import org.apache.kafka.clients.producer.KafkaProducer; |
|||
import org.apache.kafka.clients.producer.ProducerRecord; |
|||
import org.apache.kafka.clients.producer.RecordMetadata; |
|||
import org.springframework.beans.factory.annotation.Value; |
|||
|
|||
import java.util.Properties; |
|||
import java.util.concurrent.ExecutionException; |
|||
|
|||
|
|||
/** |
|||
* |
|||
*/ |
|||
@Slf4j |
|||
public class KafkaTopicProducer { |
|||
@Value("${kafka.bootstrap-servers}") |
|||
private String servers; |
|||
@Value("${kafka.producer.key-serializer}") |
|||
private String keySerializer; |
|||
@Value("${kafka.producer.value-serializer}") |
|||
private String valueSerializer; |
|||
@Value("${kafka.producer.topic}") |
|||
private String topic; |
|||
public void KafkaTopicProducer(String event) { |
|||
// 配置生产者的属性
|
|||
Properties props = new Properties(); |
|||
props.put("bootstrap.servers", servers); // Kafka broker地址
|
|||
props.put("key.serializer", keySerializer); |
|||
props.put("value.serializer",valueSerializer); |
|||
|
|||
// 创建Kafka生产者实例
|
|||
KafkaProducer<String, String> producer = new KafkaProducer<>(props); |
|||
|
|||
/* // 准备要发送的消息
|
|||
String topic = "eventAi"; |
|||
*//*String key = "key2";*//*
|
|||
String value = "这是没有key的测试信息";*/ |
|||
|
|||
try { |
|||
// 发送消息,并获取元数据(异步)
|
|||
// ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, value);
|
|||
ProducerRecord<String, String> record = new ProducerRecord<>(topic, event); |
|||
RecordMetadata metadata = producer.send(record).get(); |
|||
// 数据信息
|
|||
log.info(record.key(), record.value(), metadata.partition(), metadata.offset()); |
|||
} catch (ExecutionException | InterruptedException e) { |
|||
e.printStackTrace(); |
|||
} finally { |
|||
// 关闭生产者
|
|||
producer.close(); |
|||
} |
|||
} |
|||
} |
Loading…
Reference in new issue