package com.kafka.demo;
import java.util.Arrays;
import java.util.Properties;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;
public class SomeConsumer {
public static void main(String[] args) {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
"192.168.23.71:9092,192.168.23.72:9092,192.168.23.73:9092");
props.put(ConsumerConfig.GROUP_ID_CONFIG, "test");
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList("vehicleData"));
while (true) {
ConsumerRecords<String, String> records = consumer.poll(100);
for (ConsumerRecord<String, String> record : records) {
System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
}
}
}
}
package com.kafka.demo;
import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
public class SendMessage1 {
public static void main(String[] args) {
// 创建生产者
Properties kafkaProps = new Properties();
// 指定broker(这里指定了2个,1个备用),如果你是集群更改主机名即可,如果不是只写运行的主机名
kafkaProps.put("bootstrap.servers", "192.168.23.71:9092,192.168.23.72:9092,192.168.23.73:9092");
//kafkaProps.put("group.id", "CountryCounter"); // 消费者群组
// 设置序列化(自带的StringSerializer,如果消息的值为对象,就需要使用其他序列化方式,如Avro )
kafkaProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
kafkaProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
// 实例化出producer
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(kafkaProps);
// 创建ProducerRecord对象
ProducerRecord<String, String> record = new ProducerRecord<String, String>("vehicleData",
"Hello", "Kafka222");
try {
// 发送消息
producer.send(record);
} catch (Exception e) {
e.printStackTrace();
} finally {
producer.close();
}
}
}