在Kafka官网下载安装包kafka_2.11-1.0.0.tgz
## 解压
tar zxvf kafka_2.11-1.0.0.tgz
## 启动内置的zookeeper
.bin/zookeeper-server-start.sh ../config/zookeeper.properties
## 启动kafka
./bin/kafka-server-start.sh ../config/server.properties
创建主题
./kafka-topics.sh --create --zookeeper localhost:2181 --topic test --partitions 1 --replication-factor 1
查看主题
./kafka-topics.sh --describe --zookeeper localhost:2181 --topic test
生产消息
./kafka-console-producer.sh --broker-list localhost:9092 --topic test
消费消息
./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients -->
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka-clients</artifactId>
<version>1.0.0</version>
</dependency>
public class KafkaProducerDemo {
public static void main(String[] args) {
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("acks", "-1");
props.put("retries", 3);
props.put("batch.size", 16384);
props.put("linger.ms", 10);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("max.blocks.ms", "3000");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
for (int i = 0; i < 100; i++) {
try {
producer.send(new ProducerRecord<String, String>("testfzj", Integer.toString(i), Integer.toString(i))).get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
producer.close();
System.out.println("发送完成");
}
}
public class KafkaConsumerDemo {
public static void main(String[] args) {
String topicName = "testfzj";
String gorupId = "test-group";
Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("group.id", gorupId);
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Arrays.asList(topicName));
try {
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());
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
consumer.close();
}
}
}
使用Java客户端生产消息,出现此异常提示。
原因:外网访问,需要修改server.properties参数,将IP地址改为公网的IP地址
,然后重启服务
advertised.listeners=PLAINTEXT://59.11.11.11:9092
可参考 https://www.cnblogs.com/snifferhu/p/5102629.html
原文:https://www.cnblogs.com/fonxian/p/11837191.html