3 분 소요

0. kafka 공부 이유

  • 회사에서 초당 6만 건 이상 메시징을 처리해야 하다보니, 파이썬 멀티스레딩, redis, kafka 등에 익숙해져야 했다.

1. Kafka 개요

  • Kafka: 대용량 실시간 메시징 시스템
  • Zookeeper: Kafka 클러스터 관리 및 코디네이터 역할 (Kafka 4.x.x는 없음)
  • Broker: Kafka 서버 인스턴스
  • Topic: 메시지를 저장하는 단위

2. 사전 준비 사항

  • kafka 3.x.x는 openjdk-11-jdk, kafka 4.x.x는 openjdk-17-jdk 설치 권장
  • 인터넷 환경 (Apache Kafka 다운로드용)

3. 설치 방법(리눅스)

  1. java 설치 확인

    java -version

    • 있을 시
       openjdk version "17.0.15" 2025-04-15
       OpenJDK Runtime Environment (build 17.0.15+6-Ubuntu-0ubuntu122.04)
       OpenJDK 64-Bit Server VM (build 17.0.15+6-Ubuntu-0ubuntu122.04, mixed mode, sharing)
      
    • 없을 시
       java: command not found
      
  2. java 설치(설치된 것이 없을 시)

    apt update && apt install openjdk-17-jdk

    • 출력화면
        Get:1 http://security.ubuntu.com/ubuntu jammy-security InRelease [129 kB]
        Get:2 http://archive.ubuntu.com/ubuntu jammy InRelease [270 kB]
        Get:3 http://security.ubuntu.com/ubuntu jammy-security/restricted amd64 Packages [4976 kB]
        Get:4 http://archive.ubuntu.com/ubuntu jammy-updates InRelease [128 kB]
        Get:5 http://archive.ubuntu.com/ubuntu jammy-backports InRelease [127 kB]
        .
        .
        .
        After this operation, 567 MB of additional disk space will be used.
        Do you want to continue? [Y/n] Y
        Get:1 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 libpython3.10-minimal amd64 3.10.12-1~22.04.10 [815 kB]
        Get:2 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 libexpat1 amd64 2.4.7-1ubuntu0.6 [92.1 kB]
        Get:3 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 python3.10-minimal amd64 3.10.12-1~22.04.10 [2277 kB]
        Get:4 http://archive.ubuntu.com/ubuntu jammy-updates/main amd64 python3-minimal amd64 3.10.6-1~22.04.1 [24.3 kB]
        Get:5 http://archive.ubuntu.com/ubuntu jammy/main amd64 media-types all 7.0.0 [25.5 kB]
        .
        .
        .
        Processing triggers for ca-certificates (20240203~22.04.1) ...
        Updating certificates in /etc/ssl/certs...
        0 added, 0 removed; done.
        Running hooks in /etc/ca-certificates/update.d...
      
        done.
        done.
      
  3. kafka 설치(해당 경로에 버전 확인 필요)

    wget https://downloads.apache.org/kafka/3.5.1/kafka_2.13-4.0.0.tgz

    tar -xzf kafka_2.13-4.0.0.tgz

    mv ./kafka_2.13-4.0.0/ /opt/kafka/ (선택사항 /opt/kafka로 이동)

    • 출력화면
        --2025-07-27 08:12:25--  https://downloads.apache.org/kafka/4.0.0/kafka_2.13-4.0.0.tgz
        Resolving downloads.apache.org (downloads.apache.org)... 88.99.208.237, 135.181.214.104, 2a01:4f9:3a:2c57::2, ...
        Connecting to downloads.apache.org (downloads.apache.org)|88.99.208.237|:443... connected.
        HTTP request sent, awaiting response... 200 OK
        Length: 132045169 (126M) [application/x-gzip]
        Saving to: 'kafka_2.13-4.0.0.tgz'
      
        kafka_2.13-4.0.0.tgz          100%[=================================================>] 125.93M  3.58MB/s    in 34s
      
        2025-07-27 08:13:00 (3.72 MB/s) - 'kafka_2.13-4.0.0.tgz' saved [132045169/132045169]
      
  4. Zookeeper 실행(3.x.x 버전만 실행)

    cd /opt/kafka (경로에 맞게)

    bin/zookeeper-server-start.sh -daemon config/zookeeper.properties (-daemon 은 데몬 모드)

    • 설정파일 내부(config/zookeeper.properties)
            # 데이터 저장 경로 (로그 및 스냅샷)
            dataDir=/tmp/zookeeper
      
            # 클라이언트 포트 (Kafka와 통신하는 포트)
            clientPort=2181
      
            # Zookeeper의 최대 세션 시간(밀리초 단위)
            maxClientCnxns=60
      
            # Tick Time (Zookeeper에서 사용하는 시간 간격, 밀리초 단위)
            # 기본 단위 시간으로, 세션 시간 및 리더 선출 등에 사용됨
            tickTime=2000
      
            # initLimit: Leader가 팔로워(follower)와 초기화 시 동기화를 완료하는 데 허용하는 최대 틱(tick)수
            initLimit=10
      
            # syncLimit: 팔로워가 리더와 동기화 시 허용하는 최대 틱(tick)수
            syncLimit=5
      
  5. 클러스터 설정(4.x.x 버전만 실행)

    mkdir -p config/kraft (해당 경로가 없을 시)

    cp config/server.properties config/kraft/server.properties (설정 파일이 없을 시)

    bin/kafka-storage.sh format -t $(bin/kafka-storage.sh random-uuid) -c config/kraft/server.properties –standalone (단일 클러스터)

  6. 카프카 서버(Broker) 실행

    bin/kafka-server-start.sh -daemon config/server.properties (3.x.x버전 -daemon 은 데몬 모드)

    bin/kafka-server-start.sh -daemon config/kraft/server.properties (4.x.x버전 -daemon 은 데몬 모드)

    • 설정파일 일부(kafka 외부 노출 시키려할때 바꿔야하는 곳 : listeners, advertised.listeners)
            ############################# Socket Server Settings #############################
            .
            .
            .
            listeners=PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093
            .
            .
            .
            # Listener name, hostname and port the broker or the controller will advertise to clients.
            # If not set, it uses the value for "listeners".
            advertised.listeners=PLAINTEXT://<노출할 아이피 또는 도메인>:9092,CONTROLLER://<노출할 아이피 또는 도메인>:9093
      
  7. 토픽 추가

    bin/kafka-topics.sh –create –topic <토픽명> --partitions 3 --replication-factor 1 --bootstrap-server localhost:9092

    • 기본 커맨드:
      • --topic <토픽명>: 만들 토픽 이름 지정
      • --partitions 3: 파티션 수 (병렬성과 처리량을 높이고 싶을 때 적절히 증가)
      • --replication-factor 1: 복제본(레플리카) 개수. 단일 브로커라면 1. 다수 브로커라면 2 이상 권장.
      • --bootstrap-server localhost:9092: 사용할 브로커 주소와 포트
      • --config retention.ms=604800000 : 메세지 보관 기간 설정(현재는 7일)
  8. 여러 명령어
    • 토픽 목록 확인

      bin/kafka-topics.sh –list –bootstrap-server localhost:9092

    • 토픽 세부 정보 출력

      bin/kafka-topics.sh –describe –topic <토픽명> --bootstrap-server localhost:9092

      • 출력 화면
        Topic: nut      TopicId: ZyoUnqsnQqm4JynLZAh-fg PartitionCount: 3       ReplicationFactor: 1    Configs: segment.bytes=1073741824
          Topic: nut      Partition: 0    Leader: 1       Replicas: 1     Isr: 1  Elr:    LastKnownElr:
          Topic: nut      Partition: 1    Leader: 1       Replicas: 1     Isr: 1  Elr:    LastKnownElr:
          Topic: nut      Partition: 2    Leader: 1       Replicas: 1     Isr: 1  Elr:    LastKnownElr:
        
    • 토픽 생상

      bin/kafka-console-producer.sh –topic <토픽명> --bootstrap-server localhost:9092

      • 출력 화면(계속 입력하면 됨.)
          >
        
    • 토픽 소비

      bin/kafka-console-consumer.sh –topic <토픽명> --from-beginning --bootstrap-server localhost:9092 (--from-beginning은 맨 처음부터, default는 실시간 생산된 메세지)

      • 그룹 옵션 : –group <그룹명>
        • 컨슈머 그룹은 같은 그룹 id를 가진 여러 컨슈머 인스턴스가 하나의 논리 그룹을 이뤄, 토픽의 파티션을 나누어 병렬로 메시지를 소비할 수 있게 해줍니다.
    • 컨슈머 그룹 확인

      bin/kafka-consumer-groups.sh –list –bootstrap-server localhost:9092

    • 특정 컨슈머 그룹의 상태 확인 : 데이터 밀린 거 확인 가능

      bin/kafka-consumer-groups.sh –describe –group <그룹명> --bootstrap-server localhost:9092

      • 출력 화면
              GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID     HOST            CLIENT-ID
         neaty           nut             1          3               3               0               -               -               -
         neaty           nut             2          0               0               0               -               -               -
         neaty           nut             0          0               0               0               -               -               -
        
  9. 도커 컨테이너 세팅 시
  10. 카프카의 장점
  • 높은 처리량과 낮은 지연시간
    • 초당 수십만 건 이상의 메시지를 안정적으로 처리 가능
    • 실시간 데이터 스트림 처리에 매우 적합
    • 실시간 애널리틱스, 이벤트 기반 아키텍처 구현에 유리

태그:

카테고리:

업데이트:

댓글남기기