Apache Kafka快速演练

从容器启动

复制下面的YAML然后保存成docker-compose.yaml文件:
---
version: '3'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.0.1
    container_name: zookeeper
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:7.0.1
    container_name: broker
    ports:
    # To learn about configuring Kafka for access across networks see
    # https://www.confluent.io/blog/kafka-client-cannot-connect-to-broker-on-aws-on-docker-etc/
      - "9092:9092"
    depends_on:
      - zookeeper
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_INTERNAL:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092,PLAINTEXT_INTERNAL://broker:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
然后启动docker:
docker-compose up -d
参考:https://developer.confluent.io/quickstart/kafka-docker/

创建Topic

docker exec -it broker \
  kafka-topics --bootstrap-server broker:9092 \
               --create \
               --topic quickstart \
               --partitions 3
注:partition的个数可以不指定,默认为1个,可以后期通过alter命令进行修改。

向Topic发送消息

docker exec -it broker \
  kafka-console-producer --bootstrap-server broker:9092 \
                         --topic quickstart
输入需要发送的消息,用ENTER作为分隔,按CTRL+D结束发送。

从Topic接收消息

docker exec -it broker \
  kafka-console-consumer --bootstrap-server broker:9092 \
                         --topic quickstart
接收到消息后,就会显示在屏幕上。

从某个offset接收消息

docker exec -it broker \
  kafka-console-consumer --bootstrap-server broker:9092 \
                         --topic quickstart \
                         --offset 1 \
                         --partition 0
此时需要指定partition参数

从Topic的最开始位置接收消息

docker exec -it broker \
  kafka-console-consumer --bootstrap-server broker:9092 \
                         --topic quickstart \
                         --from-beginning

作为某个Consumer Group的客户端接收消息

docker exec -it broker \
  kafka-console-consumer --bootstrap-server broker:9092 \
                         --topic quickstart \
                         --group a
注意:
  1. 属于同一个group的不同客户端,会相继收到消息(不是轮流:https://www.confluent.io/blog/apache-kafka-2-4-latest-version-updates/#kip-480)。比如可能是Client A收到1条,然后Client B收到2条,然后再Client A收到1条
  2. 不同的group会同时收到相同的消息
 
posted @ 2022-03-19 20:56  dax.net  阅读(10)  评论(0编辑  收藏  举报