kafka

golang操作kafka与Java对比

小樊
85
2024-12-17 10:30:12
栏目: 编程语言

在当今的软件开发环境中,选择合适的编程语言来操作Apache Kafka是一个重要的决策。Go(也称为Golang)和Java都是流行的编程语言,它们在操作Kafka时各有优势和特点。以下是它们在操作Kafka时的一些对比:

Go操作Kafka

package main

import (
	"log"
	"os"
	"os/signal"
	"sync"
	"time"

	"github.com/Shopify/sarama"
)

func main() {
	config := sarama.NewConfig()
	config.Consumer.Return.Errors = true
	config.Version = sarama.V2_6_0_0

	brokers := []string{"localhost:9092"}
	groupID := "test-group"

	consumer, err := sarama.NewConsumerGroup(brokers, groupID, config)
	if err != nil {
		log.Fatalf("Error creating consumer group: %v", err)
	}
	defer consumer.Close()

	topic := "test-topic"
	handler := &consumerGroupHandler{}

	go func() {
		for {
			err := consumer.Consume(context.Background(), []string{topic}, handler)
			if err != nil {
				log.Printf("Error consuming messages: %v", err)
			}
		}
	}()

	sigterm := make(chan os.Signal, 1)
	signal.Notify(sigterm, os.Interrupt)
	<-sigterm

	consumer.Close()
}

type consumerGroupHandler struct{}

func (h *consumerGroupHandler) Setup(_ sarama.ConsumerGroupSession) error   { return nil }
func (h *consumerGroupHandler) Cleanup(_ sarama.ConsumerGroupSession) error { return nil }
func (h *consumerGroupHandler) ConsumeClaim(sess sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
	for msg := range claim.Messages() {
		log.Printf("Message: %s (partition %d, offset %d)\n", string(msg.Value), msg.Partition, msg.Offset)
		sess.MarkMessage(msg, "")
	}
	return nil
}

Java操作Kafka

Properties props = new Properties();
props.put("bootstrap.servers", "localhost:9092");
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

Producer<String, String> producer = new KafkaProducer<>(props);
ProducerRecord<String, String> record = new ProducerRecord<>("my-topic", "key", "value");
producer.send(record, new Callback() {
    public void onCompletion(RecordMetadata metadata, Exception exception) {
        if (exception != null) {
            exception.printStackTrace();
        } else {
            System.out.println("Sent message to topic: " + metadata.topic() + " partition: " + metadata.partition() + " offset: " + metadata.offset());
        }
    }
});
producer.close();

总结

选择哪种语言取决于具体的项目需求、团队熟悉度以及预期的应用场景。

0
看了该问题的人还看了