Kafka在Linux上的网络配置技巧
协议://IP:端口。若需监听所有网络接口,可使用0.0.0.0(如PLAINTEXT://0.0.0.0:9092);若需限制特定IP,替换为具体IP地址。PLAINTEXT://内网IP:9092,外网环境需替换为公网IP或映射后的域名。localhost:2181或zk1:2181,zk2:2181,zk3:2181)。为避免IP变动影响Kafka稳定性,建议设置静态IP。以Ubuntu为例,编辑/etc/netplan/01-netcfg.yaml文件:
network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: no
addresses: ["192.168.1.100/24"] # 替换为你的静态IP和子网掩码
gateway4: "192.168.1.1" # 替换为你的网关
nameservers:
addresses: ["8.8.8.8", "8.8.4.4"] # 替换为你的DNS服务器
保存后执行sudo netplan apply使配置生效。
允许Kafka端口(默认9092)通过防火墙,以Ubuntu(ufw)为例:
sudo ufw allow 9092/tcp # 允许TCP协议的9092端口
sudo ufw enable # 启用防火墙(若未启用)
若使用CentOS(firewalld),可执行:
sudo firewall-cmd --permanent --add-port=9092/tcp # 永久添加端口
sudo firewall-cmd --reload # 重新加载规则
编辑/etc/sysctl.conf文件,优化TCP性能:
net.core.rmem_max = 16777216 # 接收缓冲区最大值(16MB)
net.core.wmem_max = 16777216 # 发送缓冲区最大值(16MB)
net.ipv4.tcp_rmem = 4096 87380 16777216 # 接收缓冲区动态调整范围
net.ipv4.tcp_wmem = 4096 65536 16777216 # 发送缓冲区动态调整范围
net.ipv4.tcp_no_metrics_save = 1 # 禁止保存TCP metrics,减少内存占用
net.ipv4.tcp_low_latency = 1 # 优先保证低延迟
应用配置:sudo sysctl -p。
/etc/security/limits.conf,添加以下内容(允许用户无限制打开文件):* soft nofile 65536
* hard nofile 65536
server.properties中设置:num.network.threads=3 # 网络线程数(建议为CPU核心数的2倍)
num.io.threads=8 # I/O线程数(根据磁盘数量和性能调整)
socket.send.buffer.bytes=1048576 # 发送缓冲区(1MB)
socket.receive.buffer.bytes=1048576 # 接收缓冲区(1MB)
Kafka支持gzip、snappy、lz4等压缩算法,可减少网络传输数据量。在server.properties中配置:
compression.type=snappy # 推荐使用snappy(平衡压缩率与CPU消耗)
或在生产者/消费者端单独配置(如producer.properties中设置compression.type=gzip)。
若Kafka部署在同时接入内网和外网的服务器上,可通过listener.security.protocol.map实现流量隔离:
listeners=INTERNAL://192.168.88.12:9092,EXTERNAL://192.168.100.104:19092 # 内网和外网监听地址
advertised.listeners=INTERNAL://192.168.88.12:9092,EXTERNAL://192.168.100.104:19092 # 对外暴露的地址
inter.broker.listener.name=INTERNAL # broker间通信使用内网协议
listener.security.protocol.map=INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT # 协议映射(生产环境建议用SSL)
此配置可确保内网客户端通过INTERNAL协议访问,外网客户端通过EXTERNAL协议访问,提升安全性与性能。
bin文件夹,执行:./kafka-server-start.sh ../config/server.properties
./kafka-topics.sh --create --topic test_topic --bootstrap-server localhost:9092
./kafka-console-producer.sh --topic test_topic --bootstrap-server localhost:9092./kafka-console-consumer.sh --topic test_topic --from-beginning --bootstrap-server localhost:9092