Go 언어 Redpanda Consume 예제 코드

Redpanda는 Kafka API와 호환되기 때문에 Go에서 Kafka 클라이언트 라이브러리(예: franz-go, sarama)를 사용할 수 있습니다. 아래는 대표적인 franz-go와 sarama를 활용한 Redpanda consumer 예제 코드입니다.

1. franz-go를 이용한 Redpanda Consumer 예제

gopackage main

import (
    "context"
    "fmt"
    "github.com/twmb/franz-go/pkg/kgo"
)

func main() {
    // Redpanda 브로커 주소와 토픽, 그룹 설정
    opts := []kgo.Opt{
        kgo.SeedBrokers("localhost:9092"), // Redpanda 브로커 주소
        kgo.ConsumerGroup("my-group-id"),  // Consumer group id
        kgo.ConsumeTopics("my-topic"),     // 구독할 토픽
    }

    client, err := kgo.NewClient(opts...)
    if err != nil {
        panic(err)
    }
    defer client.Close()

    ctx := context.Background()
    for {
        // 메시지 폴링
        fetches := client.PollFetches(ctx)
        if errs := fetches.Errors(); len(errs) > 0 {
            for _, err := range errs {
                fmt.Printf("Error: %v\n", err)
            }
            continue
        }
        // 메시지 출력
        fetches.EachRecord(func(record *kgo.Record) {
            fmt.Printf("Topic: %s, Partition: %d, Offset: %d, Value: %s\n",
                record.Topic, record.Partition, record.Offset, string(record.Value))
        })
    }
}

이 예제는 franz-go 라이브러리를 사용하여 Redpanda에서 메시지를 지속적으로 소비합니다24.

2. Sarama를 이용한 Redpanda Consumer 예제

Sarama를 활용한 예제는 아래와 같습니다. 실제 전체 코드는 webtoor/go-redpanda-example에서 확인할 수 있습니다.

gopackage main

import (
    "fmt"
    "github.com/Shopify/sarama"
)

func main() {
    brokers := []string{"localhost:9092"}
    topic := "my-topic"

    config := sarama.NewConfig()
    config.Consumer.Return.Errors = true

    master, err := sarama.NewConsumer(brokers, config)
    if err != nil {
        panic(err)
    }
    defer master.Close()

    consumer, err := master.ConsumePartition(topic, 0, sarama.OffsetNewest)
    if err != nil {
        panic(err)
    }
    defer consumer.Close()

    for msg := range consumer.Messages() {
        fmt.Printf("Topic: %s, Partition: %d, Offset: %d, Value: %s\n",
            msg.Topic, msg.Partition, msg.Offset, string(msg.Value))
    }
}

이 코드는 Sarama 라이브러리를 이용해 Redpanda에서 메시지를 읽어오는 기본적인 예제입니다5.

참고 자료 및 예제 코드 위치

  • 공식 Redpanda Go 예제 및 실습:
    git clone https://github.com/redpanda-data/redpanda-labs.gitclients/chat-room/docker/go/consumer.go 참고1.
  • 다양한 Go 예제 모음:
    https://github.com/redpanda-data/redpanda-examples3
  • Sarama 기반 예제:
    https://github.com/webtoor/go-redpanda-example5

요약

  • Redpanda는 Kafka API 호환이므로, Go의 Kafka 클라이언트(franz-go, sarama 등)로 쉽게 Consume이 가능합니다.
  • 공식 예제 및 오픈소스 프로젝트를 참고하면 실전 적용에 도움이 됩니다.

Citations:

  1. https://docs.redpanda.com/redpanda-labs/clients/docker-go/
  2. https://aran.dev/posts/getting-started-with-golang-and-kafka/
  3. https://github.com/redpanda-data/redpanda-examples
  4. https://callistaenterprise.se/blogg/teknik/2023/01/16/kafka-go-1-consuming-messages/
  5. https://github.com/webtoor/go-redpanda-example
  6. https://www.redpanda.com/guides/kafka-tutorial-kafka-console-consumer
  7. https://golang.testcontainers.org/modules/redpanda/
  8. https://www.redpanda.com/blog/python-redpanda-kafka-api-tutorial
  9. https://www.reddit.com/r/golang/comments/1dh4q4s/go_client_for_kafka/
  10. https://www.redpanda.com/guides/kafka-tutorial-kafka-consumer-config
  11. https://docs.redpanda.com/redpanda-labs/clients/cloud-go/
  12. https://www.redpanda.com/guides/kafka-architecture-kafka-client
  13. https://github.com/twmb/franz-go
  14. https://www.redpanda.com/blog/produce-consume-apache-avro-tutorial
  15. https://docs.redpanda.com/current/reference/rpk/rpk-topic/rpk-topic-consume/
  16. https://patrickdesjardins.com/blog/typescript-consuming-producing-redpanda-message
  17. https://www.redpanda.com/guides/kafka-architecture-kafka-consumer-group

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

Back to top