springboot集成kafka
kafka介绍
Kafka本身是Scala编写的,运行在JVM之上。Producer和Consumer都通过Kafka的客户端使用网络来与之通信。从逻辑上讲,Kafka设计非常简单,它只有一种类似JMS的Topic的消息通道:
那么Kafka如何支持十万甚至百万的并发呢?答案是分区。Kafka的一个Topic可以有一个至多个Partition,并且可以分布到多台机器上:
Kafka只保证在一个Partition内部,消息是有序的,但是,存在多个Partition的情况下,Producer发送的3个消息会依次发送到Partition-1、Partition-2和Partition-3,Consumer从3个Partition接收的消息并不一定是Producer发送的顺序,因此,多个Partition只能保证接收消息大概率按发送时间有序,并不能保证完全按Producer发送的顺序。这一点在使用Kafka作为消息服务器时要特别注意,对发送顺序有严格要求的Topic只能有一个Partition。
Kafka的另一个特点是消息发送和接收都尽量使用批处理,一次处理几十甚至上百条消息,比一次一条效率要高很多。
最后要注意的是消息的持久性。Kafka总是将消息写入Partition对应的文件,消息保存多久取决于服务器的配置,可以按照时间删除(默认3天),也可以按照文件大小删除,因此,只要Consumer在离线期内的消息还没有被删除,再次上线仍然可以接收到完整的消息流。这一功能实际上是客户端自己实现的,客户端会存储它接收到的最后一个消息的offsetId,再次上线后按上次的offsetId查询。offsetId是Kafka标识某个Partion的每一条消息的递增整数,客户端通常将它存储在ZooKeeper中。
有了Kafka消息设计的基本概念,我们来看看如何在Spring Boot中使用Kafka。
环境准备
centos7,idea,jdk1.8+
安装kafka
下载:
wget https://mirrors.bfsu.edu.cn/apache/kafka/2.4.1/kafka_2.11-2.4.1.tgz
解压:
tar -zxvf kafka_2.11-2.4.1.tgz
进入:
修改server.properties
[root@localhost config]# pwd /home/lpg/kafka/kafka_2.11-2.4.1/config vi server.properties
#以下需要关注红色部分,尤其是地址,最好填写真实的ip
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # see kafka.server.KafkaConfig for additional details and defaults ############################# Server Basics ############################# # The id of the broker. This must be set to a unique integer for each broker. broker.id=0 ############################# Socket Server Settings ############################# # 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://:9092 # 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://我的ip:9092 # Maps listener names to security protocols, the default is for them to be the same. See the config documentation for more details #listener.security.protocol.map=PLAINTEXT:PLAINTEXT,SSL:SSL,SASL_PLAINTEXT:SASL_PLAINTEXT,SASL_SSL:SASL_SSL # The number of threads that the server uses for receiving requests from the network and sending responses to the network num.network.threads=3 # The number of threads that the server uses for processing requests, which may include disk I/O num.io.threads=8 # The send buffer (SO_SNDBUF) used by the socket server socket.send.buffer.bytes=102400 # The receive buffer (SO_RCVBUF) used by the socket server socket.receive.buffer.bytes=102400 # The maximum size of a request that the socket server will accept (protection against OOM) socket.request.max.bytes=104857600 ############################# Log Basics ############################# # A comma separated list of directories under which to store log files log.dirs=/home/lpg/kafka/kafka_2.11-2.4.1/kafka-logs # The default number of log partitions per topic. More partitions allow greater # parallelism for consumption, but this will also result in more files across # the brokers. num.partitions=1 # The number of threads per data directory to be used for log recovery at startup and flushing at shutdown. # This value is recommended to be increased for installations with data dirs located in RAID array. num.recovery.threads.per.data.dir=1 ############################# Internal Topic Settings ############################# # The replication factor for the group metadata internal topics "__consumer_offsets" and "__transaction_state" # For anything other than development testing, a value greater than 1 is recommended to ensure availability such as 3. offsets.topic.replication.factor=1 transaction.state.log.replication.factor=1 transaction.state.log.min.isr=1 ############################# Log Flush Policy ############################# # Messages are immediately written to the filesystem but by default we only fsync() to sync # the OS cache lazily. The following configurations control the flush of data to disk. # There are a few important trade-offs here: # 1. Durability: Unflushed data may be lost if you are not using replication. # 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. # 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to excessive seeks. # The settings below allow one to configure the flush policy to flush data after a period of time or # every N messages (or both). This can be done globally and overridden on a per-topic basis. # The number of messages to accept before forcing a flush of data to disk #log.flush.interval.messages=10000 # The maximum amount of time a message can sit in a log before we force a flush #log.flush.interval.ms=1000 ############################# Log Retention Policy ############################# # The following configurations control the disposal of log segments. The policy can # be set to delete segments after a period of time, or after a given size has accumulated. # A segment will be deleted whenever *either* of these criteria are met. Deletion always happens # from the end of the log. # The minimum age of a log file to be eligible for deletion due to age log.retention.hours=168 # A size-based retention policy for logs. Segments are pruned from the log unless the remaining # segments drop below log.retention.bytes. Functions independently of log.retention.hours. #log.retention.bytes=1073741824 # The maximum size of a log segment file. When this size is reached a new log segment will be created. log.segment.bytes=1073741824 # The interval at which log segments are checked to see if they can be deleted according # to the retention policies log.retention.check.interval.ms=300000 ############################# Zookeeper ############################# # Zookeeper connection string (see zookeeper docs for details). # This is a comma separated host:port pairs, each corresponding to a zk # server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". # You can also append an optional chroot string to the urls to specify the # root directory for all kafka znodes. zookeeper.connect=zk机器ip:2181 # Timeout in ms for connecting to zookeeper zookeeper.connection.timeout.ms=6000 ############################# Group Coordinator Settings ############################# # The following configuration specifies the time, in milliseconds, that the GroupCoordinator will delay the initial consumer rebalance. # The rebalance will be further delayed by the value of group.initial.rebalance.delay.ms as new members join the group, up to a maximum of max.poll.interval.ms. # The default value for this is 3 seconds. # We override this to 0 here as it makes for a better out-of-the-box experience for development and testing. # However, in production environments the default value of 3 seconds is more suitable as this will help to avoid unnecessary, and potentially expensive, rebalances during application startup. group.initial.rebalance.delay.ms=0
安装zk
下载zk:zookeeper-3.4.12.tar.gz
解压:tar -zxvf apache-zookeeper-3.6.2-bin.tar.gz
进入zk的conf目录:cd conf/
拷贝生成zoo.cfg:cp zoo_sample.cfg zoo.cfg
修改zoo.cfg文件:
# The number of milliseconds of each tick tickTime=2000 # The number of ticks that the initial # synchronization phase can take initLimit=10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit=5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. # The number of ticks that the initial # synchronization phase can take initLimit=10 # The number of ticks that can pass between # sending a request and getting an acknowledgement syncLimit=5 # the directory where the snapshot is stored. # do not use /tmp for storage, /tmp here is just # example sakes. dataDir=/home/lpg/zookeeper/apache-zookeeper-3.6.2-bin/data # the port at which the clients will connect clientPort=2181 # the maximum number of client connections. # increase this if you need to handle more clients #maxClientCnxns=60 # # Be sure to read the maintenance section of the # administrator guide before turning on autopurge. # # http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance # # The number of snapshots to retain in dataDir #autopurge.snapRetainCount=3 # Purge task interval in hours # Set to "0" to disable auto purge feature
#此处可配置集群节点,此处忽略
#server.1=172.17.3.205:2888:3888
#server.2=172.17.3.206:2888:3888
#server.3=172.17.3.207:2888:3888
安装KafkaOffsetMonitor
KafkaOffsetMonitor是Kafka的一款客户端消费监控工具,用来实时监控Kafka服务的Consumer以及它们所在的Partition中的Offset,我们可以浏览当前的消费者组,并且每个Topic的所有Partition的消费情况都可以一目了然。
下载jar包:KafkaOffsetMonitor-assembly-0.2.0.jar 即可
启动各个服务
按照顺序启动如下服务:
zk:进入bin目录,执行:./zkServer.sh start
kafka:进入bin目录,执行:./kafka-server-start.sh ../config/server.properties
KafkaOffsetMonitor:进入jar包所在目录,执行:java -cp KafkaOffsetMonitor-assembly-0.2.0.jar com.quantifind.kafka.offsetapp.OffsetGetterWeb --zk localhost:2181 --port 8089 --refresh 10.seconds --retain 1.days
与springboot整合
pom依赖
<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency>
application.yml配置
server: port: 7889 spring: kafka: bootstrap-servers: 172.22.3.14:9092 producer: retries: 0 batch-size: 16384 buffer-memory: 33554432 key-serializer: org.apache.kafka.common.serialization.StringSerializer value-serializer: org.apache.kafka.common.serialization.StringSerializer properties: linger.ms: 1 consumer: enable-auto-commit: false auto-commit-interval: 100ms key-deserializer: org.apache.kafka.common.serialization.StringDeserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer properties: session.timeout.ms: 15000 group-id: test-group-id
解释下以上属性含义:
bootstrap-servers:连接kafka的地址,多个地址用逗号分隔 batch-size:当将多个记录被发送到同一个分区时, Producer 将尝试将记录组合到更少的请求中。这有助于提升客户端和服务器端的性能。这个配置控制一个批次的默认大小(以字节为单位)。16384是缺省的配置 retries:若设置大于0的值,客户端会将发送失败的记录重新发送 buffer-memory:Producer 用来缓冲等待被发送到服务器的记录的总字节数,33554432是缺省配置 key-serializer:关键字的序列化类 value-serializer:值的序列化类
生产与消费
package com.lpg.kafka.service; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.SendResult; import org.springframework.stereotype.Service; import org.springframework.util.concurrent.ListenableFuture; import org.springframework.util.concurrent.ListenableFutureCallback; /** * @author lpg * @description: kfk生产者与消费者 * @date 2020-12-2317:57 */ @Service @Slf4j public class KfkService { @Autowired private KafkaTemplate<Integer,String> kafkaTemplate; //消费者:监听topic1,groupId1 @KafkaListener(topics = {"topic1"},groupId = "groupId1") public void consumer1(ConsumerRecord<Integer,String> record){ log.info("consumer1 kfk consume message start..."); log.info("consumer1 kfk consume message topic:{},msg:{}",record.topic(),record.value()); log.info("consumer1 kfk consume message end..."); } //消费者:监听topic1,groupId2 @KafkaListener(topics = {"topic1"},groupId = "groupId2") public void consumer3(ConsumerRecord<Integer,String> record){ log.info("consumer3 kfk consume message start..."); log.info("consumer3 kfk consume message topic:{},msg:{}",record.topic(),record.value()); log.info("consumer3 kfk consume message end..."); } //消费者:监听topic1,groupId2 @KafkaListener(topics = {"topic1"},groupId = "groupId2") public void consumer2(ConsumerRecord<Integer,String> record){ log.info("consumer2 kfk consume message start..."); log.info("consumer2 kfk consume message topic:{},msg:{}",record.topic(),record.value()); log.info("consumer2 kfk consume message end..."); } //生产者 public void sendMsg(String topic , String msg){ log.info("开始发送kfk消息,topic:{},msg:{}",topic,msg); ListenableFuture<SendResult<Integer, String>> sendMsg = kafkaTemplate.send(topic, msg); //消息确认 sendMsg.addCallback(new ListenableFutureCallback<SendResult<Integer, String>>() { @Override public void onFailure(Throwable throwable) { log.error("send error,ex:{},topic:{},msg:{}",throwable,topic,msg); } @Override public void onSuccess(SendResult<Integer, String> stringStringSendResult) { log.info("send success,topic:{},msg:{}",topic,msg); } }); log.info("kfk send end!"); } }
测试
package com.lpg.kafka.controller; import com.lpg.kafka.service.KfkService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author lpg * @description: 测试kfk生产与消费 * @date 2020-12-2318:22 */ @RestController public class KfkController { @Autowired private KfkService kfkService; @GetMapping("/send") public String send(){ kfkService.sendMsg("topic1","I am topic msg"); return "success-topic1"; } }
启动idea服务
启动之后,浏览器输入http://localhost:7889/send
运行结果如下:
从上面测试结果,可以印证:同一group的topic只允许一个线程来消费。
monitor插件监控
浏览器输入http://ip:8089/#/