项目作者: irisgve

项目描述 :
Simple producer and consumer clients in Java with Kafka docker setup
高级语言: Java
项目地址: git://github.com/irisgve/simple-kafka-clients.git
创建时间: 2020-02-09T11:21:35Z
项目社区:https://github.com/irisgve/simple-kafka-clients

开源协议:

下载


Kafka Producer and Consumer in Java

Prerequisites

If you already have Java and Maven installed, make sure you have:

  • Java 8 (you can get away with Java 7 until we get to streaming)
  • Maven 3.X

Running Kafka

  1. Start the Kafka and Zookeeper processes using Docker Compose in docker/:

    1. $ docker-compose up
  2. The sample clients require that you create two topics that will be used in the Producer program. Run the following commands:

    1. $ docker-compose exec kafka /opt/kafka/bin/kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic user-events
    2. $ docker-compose exec kafka /opt/kafka/bin/kafka-topics.sh --create --zookeeper zookeeper:2181 --replication-factor 1 --partitions 1 --topic global-events
  3. List the topics to double check they were created without any issues.

    1. $ docker-compose exec kafka /opt/kafka/bin/kafka-topics.sh --list --zookeeper zookeeper:2181
    2. global-events
    3. user-events

Running the Clients

  1. Inside the producer/ package, run mvn:

    1. $ mvn clean package
  2. For convenience, the project is set up so that the package target produces a single executable: target/producer. Run the producer to send messages to our two topics — user-events and global-events.

    1. $ target/producer
    2. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    3. SLF4J: Defaulting to no-operation (NOP) logger implementation
    4. SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    5. Sent message number 0
    6. Sent message number 100
    7. ...
    8. Sent message number 99800
    9. Sent message number 99900
  3. Inside the consumer/ package, run mvn:

    1. $ mvn clean package
  4. For convenience, the project is set up so that the package target produces a single executable: target/consumer. Run the consumer:

    1. $ target/consumer
    2. SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    3. SLF4J: Defaulting to no-operation (NOP) logger implementation
    4. SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    5. Received user-events message - key: user_id_0 value: some_value_148511272601285
    6. Received user-events message - key: user_id_1 value: some_value_148511557371815
    7. Received user-events message - key: user_id_2 value: some_value_148511557456741
    8. ....

    After the consumer has processed all of the messages, start the producer again in another terminal window and you will see the consumer output the messages almost immediately. The consumer will run indefinitely until you press Ctrl-C in the terminal window.