关于kafka的入门,可以阅读这篇教程。下面主要讲述博主在安装过程中遇到的问题:
java.net.InetAddress.getCanonicalHostName()
获取主机名(默认的端口是9092),获取到的这个主机名所对应的ip很可能是127.0.0.1,从而导致broker之间是不能互相通信的,解决方法是:
<dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>0.10.1.0</version> </dependency>
import java.util.Properties; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; public class MyProducer { public static void main( String[] args ) { Properties props = new Properties(); props.put("bootstrap.servers", "192.168.100.101:9092,192.168.100.102:9092"); props.put("acks", "all"); props.put("retries", 0); props.put("batch.size", 10); props.put("linger.ms", 1); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); Producerproducer = new KafkaProducer (props); for(int i=0;i<100;i++){ ProducerRecord r = new ProducerRecord ("test.message","key-"+i,"value-"+i); System.out.println(r); producer.send(r); } producer.close(); } }
import java.util.Arrays; import java.util.Properties; import org.apache.kafka.clients.consumer.Consumer; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; public class MyConsumer { public static void main(String[] args) { Properties props = new Properties(); props.put("bootstrap.servers", "192.168.100.102:9092,192.168.100.103:9092,192.168.100.101:9092"); props.put("group.id", "TestGroupA"); props.put("enable.auto.commit", "true"); props.put("auto.commit.interval.ms", "1000"); props.put("session.timeout.ms", "30000"); props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); Consumerconsumer = new KafkaConsumer (props); consumer.subscribe(Arrays.asList("test.message")); while(true){ ConsumerRecords records = consumer.poll(10); for(ConsumerRecord record : records){ System.out.println("offset=" + record.offset() + ",--key=" + record.key() + ",--value=" + record.value()); } } } }