先来解释一下这两个参数的含义:
# 49.232.162.235是我的本机公网ip
打开文件 vi server.properties
# The address the socket server listens on. It will get the value returned from
# java.net.InetAddress.getCanonicalHostName() if not configured.
# FORMAT:
# listeners = listener_name://host_name:port
# EXAMPLE:
# listeners = PLAINTEXT://your.host.name:9092
#listeners=PLAINTEXT://localhost:9092
listeners是kafka通讯的IP和端口,当然是本机地址了,这里不用改,不用改,不用改。
# Hostname and port the broker will advertise to producers and consumers. If not set,
# it uses the value for "listeners" if configured. Otherwise, it will use the value
# returned from java.net.InetAddress.getCanonicalHostName().
advertised.listeners=PLAINTEXT://49.232.162.235:9092
advertised.listeners是kafka注册到zookeeper的地址,然后对公网暴露的地址。
你在java-kafka-client中访问的地址必须是这里填的地址。所以一般情况下这里都是填本机的IP公网地址。
要保证防火墙是关闭的,zookeeper启动是正常的,和kafka在同一台机器上运行的。
总结一下就是:
listeners不需要改, advertised.listeners改成你的ip地址。
最后我贴一下我的java-client-kafka代码
import org.apache.kafka.clients.producer.*;
import java.util.Properties;
public class MsgProducer {
public static void main(String[] args) {
String KafkaURI = "49.232.162.235:9092";
Properties props = new Properties();
props.put("bootstrap.servers", KafkaURI);
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
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");
Producer<String, String> producer = new KafkaProducer<String, String>(props);
//生产者 topic key
producer.send(new ProducerRecord<String, String>("web_log", "data from java-client"));
producer.close();
}
}
如果到现在你还是连不上,执行下面命令看一下你的9092端口是不是正常。
[root@VM_0_9_centos config]# netstat -tunlp | grep 9092
tcp6 0 0 :::9092 :::* LISTEN 2604/java
上面的第四个参数 :::9092 表示ipv6的对公网访问,0.0.0.0是ipv4的对公网访问,如果是127.0.0.1表示只对本地访问,那你的java-client肯定就访问不到。
很可能还是listeners配置的问题,注释掉就可以了。
有问题欢迎评论留言,不定时回复!