Kafka学习笔记

我们两清 提交于 2020-03-08 01:03:10

zk启动

bin/zkServer.sh start

后台启动kafka

bin/kafka-server-start.sh config/server.properties 1>/dev/null 2>&1 &

测试生产者消费者

创建主题
bin/kafka-topics.sh --zookeeper localhost:2181 --create --topic calvin --partitions 2 --replication-factor 1

查看所有主题
bin/kafka-topics.sh --zookeeper localhost:2181 --list

查看对应的主题
bin/kafka-topics.sh --zookeeper localhost:2181 --describe --topic calvin

指定生产者发送消息到主题
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic calvin

指定消费者订阅主题
bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic calvin

单机版注意一个坑,需要 将server.properties设置advertised.listeners=PLAINTEXT://your.host.name:9092

改为kafka所在机器的ip,即:

advertised.listeners=PLAINTEXT://192.168.0.8:9092

否则Java应用去连接kafka,发现会连接出错,报如下的错误:

org.apache.kafka.common.network.Selector - [Producer clientId=producer-1] Connection with localhost/127.0.0.1 disconnected

异步发送

producer.send(record, (metadata, e) -> {
    if (e == null) {
      System.out.println("topic:" + metadata.topic());
      System.out.println("partition:" + metadata.partition());
      System.out.println("offset:" + metadata.offset());
    }
});

发送原理

消息发送的过程中,涉及到两个线程协同工作,主线程首先将业务数据封装成ProducerRecord对象,
之后调用send()方法将消息放入RecordAccumulator(消息收集器,也可以理解为主线程与Sender线程
直接的缓冲区)中暂存,Sender线程负责将消息信息构成请求,并最终执行网络I/O的线程,它从
RecordAccumulator中取出消息并批量发送出去,需要注意的是,KafkaProducer是线程安全的,多个
线程间可以共享使用同一个KafkaProducer对象。

zookeeper集群搭建

2888端口号是zookeeper服务之间通信的端口
3888端口是zookeeper与其他应用程序通信的端口。

# 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.
dataDir=/tmp/zookeeper-01/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
#autopurge.purgeInterval=1
server.0=192.168.0.8:2888:3888
server.1=192.168.0.9:2888:3888
server.2=192.168.0.10:2888:3888

不同的节点分别修改dataDir

/tmp/zookeeper-01/data包下
touch myid
vi myid
写入0保存

其他两个节点分别为1,2

kafka集群搭建

# 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
listeners=PLAINTEXT://192.168.0.8: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://192.168.0.8: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=/tmp/kafka-01/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 for 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=localhost:2181
zookeeper.connect=192.168.0.8:2181,192.168.0.9:2181,192.168.0.10: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

其他两个节点对应修改即可

创建主题验证,创建三个分区三个副本

bin/kafka-topics.sh --zookeeper 192.168.0.8:2181 --create --topic kafka-cluster --partitions 3 --replication-factor 3

查看对应的主题,验证集群搭建是否成功

bin/kafka-topics.sh --zookeeper 192.168.0.8:2181 --describe --topic kafka-cluster

可以看到如下的主题分区副本信息,说明kafka集群搭建成功。

[root@localhost kafka-01]# bin/kafka-topics.sh --zookeeper 192.168.0.8:2181 --describe --topic kafka-cluster
Topic:kafka-cluster     PartitionCount:3        ReplicationFactor:3     Configs:
        Topic: kafka-cluster    Partition: 0    Leader: 2       Replicas: 2,0,1 Isr: 2,0,1
        Topic: kafka-cluster    Partition: 1    Leader: 0       Replicas: 0,1,2 Isr: 0,1,2
        Topic: kafka-cluster    Partition: 2    Leader: 1       Replicas: 1,2,0 Isr: 1,2,0

给topic增加分区,注意只能增加不能减少

bin/kafka-topics.sh --alter --zookeeper 192.168.0.8:2181 --topic kafka-cluster --partitions 4

再次查看主题信息,发现已经新增分区完成。

[root@localhost kafka-01]# bin/kafka-topics.sh --zookeeper 192.168.0.8:2181 --describe --topic kafka-cluster
Topic:kafka-cluster     PartitionCount:4        ReplicationFactor:3     Configs:
        Topic: kafka-cluster    Partition: 0    Leader: 2       Replicas: 2,0,1 Isr: 2,0,1
        Topic: kafka-cluster    Partition: 1    Leader: 0       Replicas: 0,1,2 Isr: 0,1,2
        Topic: kafka-cluster    Partition: 2    Leader: 1       Replicas: 1,2,0 Isr: 1,2,0
        Topic: kafka-cluster    Partition: 3    Leader: 2       Replicas: 2,1,0 Isr: 2,1,0

Kafka的Message存储采用了分区(partition),分段(LogSegment)和稀疏索引这几个手段来达到了高效性。

Kafka幂等性,默认该配置参数就是true。

Properties props = new Properties(); 
props.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, "true");

Kafka事务

package com.calvin.exercise.kafka;

import java.util.Properties;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

/**
 * @Title ProducerTransactionSend
 * @Description kafka事务发送
 * @author calvin
 * @date: 2020/3/6 4:50 PM 
 */
public class ProducerTransactionSend {

    // Kafka集群地址

    private static final String brokerList = "192.168.0.8:9092";

    // 主题名称-之前已经创建
    private static final String topic = "calvin";

    private static final String transactionId = "transactionId";

    public static void main(String[] args) {

        Properties properties = new Properties();
        // 设置key序列化器
        properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        // 设置值序列化器
        properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        // 设置集群地址
        properties.put("bootstrap.servers", brokerList);
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, transactionId);
        // KafkaProducer 线程安全
        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);
        // 初始化事务
        producer.initTransactions();
        // 开启事务
        producer.beginTransaction();
        try {
            ProducerRecord<String, String> record1 = new ProducerRecord<>(topic, "message-1");
            producer.send(record1);

            ProducerRecord<String, String> record2 = new ProducerRecord<>(topic, "message-2");
            producer.send(record2);

            ProducerRecord<String, String> record3 = new ProducerRecord<>(topic, "message-3");
            producer.send(record3);
        } catch (Exception e) {
            producer.abortTransaction();
        } finally {
            producer.close();
        }
    }

}

Kafka与SpringBoot整合

application.yml

spring:
  kafka:
    producer:
      bootstrap-servers: 192.168.0.8:9092,192.168.0.9:9092,192.168.0.10:9092
      transaction-id-prefix: kafka-tx
    consumer:
      bootstrap-servers: 192.168.0.8:9092,192.168.0.9:9092,192.168.0.10:9092

pom.xml引入依赖

<dependency>
  <groupId>org.springframework.kafka</groupId>
  <artifactId>spring-kafka</artifactId>
</dependency>

发送与接收消息

package com.calvin.exercise.kafka;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Title KafkaController
 * @Description
 * @author calvin
 * @date: 2020/3/7 4:24 PM
 */

@RestController
public class KafkaController {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping("send/{message}")
    public String sendMessage(@PathVariable String message) {
        kafkaTemplate.send("calvin",message);
        return "send success" + message;
    }

    @KafkaListener(id = "", topics = "calvin", groupId = "group.demo")
    public void getMessage(String message) {
        System.out.println("message = " + message);
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!