Documentation
¶
Overview ¶
Package kafka provides a testable Kafka producer and consumer library built on top of confluent-kafka-go/v2.
Unlike the PHP static-method approach, this package uses interfaces for both the Producer and Consumer, as well as for the underlying Kafka client and Logger. This makes it straightforward to mock in unit tests without needing a real Kafka broker.
Usage example (Producer):
cfg := &kafka.ProducerConfig{
Brokers: "broker1:9092,broker2:9092",
Username: "user",
Password: "pass",
}
p, err := kafka.NewProducer(cfg, nil) // nil uses default logger
if err != nil {
log.Fatal(err)
}
defer p.Close()
err = p.Publish(ctx, "my-topic", []byte("key"), []byte(`{"data":"value"}`), nil)
Usage example (Consumer):
cfg := &kafka.ConsumerConfig{
Brokers: "broker1:9092,broker2:9092",
Username: "user",
Password: "pass",
GroupID: "my-consumer-group",
Topics: []string{"my-topic"},
}
c, err := kafka.NewConsumer(cfg, nil)
if err != nil {
log.Fatal(err)
}
defer c.Close()
err = c.Subscribe()
if err != nil {
log.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
err = c.Consume(ctx, func(ctx context.Context, msg *kafka.Message) error {
fmt.Printf("Received: %s\n", string(msg.Value))
return nil
})
Testing example:
// Use NewProducerWithClient or NewConsumerWithClient with a mock client
mockClient := &MockKafkaProducerClient{}
p := kafka.NewProducerWithClient(mockClient, cfg, &kafka.NopLogger{})
Index ¶
- Constants
- type Consumer
- type ConsumerConfig
- type Header
- type KafkaConsumerClient
- type KafkaProducerClient
- type Logger
- type Message
- type MessageHandler
- type NopLogger
- func (l *NopLogger) OnCommitError(topic string, partition int32, offset int64, err error)
- func (l *NopLogger) OnCommitSuccess(topic string, partition int32, offset int64)
- func (l *NopLogger) OnConsume(topic string, partition int32, offset int64, key []byte)
- func (l *NopLogger) OnConsumeError(topic string, key []byte, err error)
- func (l *NopLogger) OnDeliveryFailed(topic string, key []byte, err error)
- func (l *NopLogger) OnDeliverySuccess(topic string, partition int32, offset kafka.Offset, key []byte)
- func (l *NopLogger) OnError(component string, err kafka.Error)
- func (l *NopLogger) OnLog(level int, facility string, message string)
- func (l *NopLogger) OnProduceError(topic string, key []byte, err error)
- func (l *NopLogger) OnRebalance(partitions []kafka.TopicPartition, assigned bool)
- type Producer
- type ProducerConfig
Constants ¶
const ( // Schemaless means no schema and no serialization mechanism. Schemaless = 1 // SchemalessWithSerde means no schema but has JSON encode/decode mechanism. SchemalessWithSerde = 2 // SchemafullWithSerde means has schema (Avro) and encode/decode mechanism. SchemafullWithSerde = 3 )
SchemaType determines the serialization behavior of the message.
const Version = "1.0.0"
Version is the version of this kafka package.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Consumer ¶
type Consumer interface {
// Subscribe subscribes the consumer to the configured topics.
Subscribe() error
// Poll polls for a single message. Returns nil if timeout is reached without a message.
Poll(timeoutMs int) (*Message, error)
// Consume starts consuming messages and invokes the handler for each message.
// This is a blocking call that runs until the context is cancelled.
Consume(ctx context.Context, handler MessageHandler) error
// CommitMessage commits the offset of the given message.
CommitMessage(msg *Message) error
// Close gracefully shuts down the consumer.
Close() error
}
Consumer defines the interface for consuming messages from Kafka. This interface enables mocking in unit tests.
func NewConsumer ¶
func NewConsumer(config *ConsumerConfig, logger Logger) (Consumer, error)
NewConsumer creates a new Kafka consumer instance.
func NewConsumerWithClient ¶
func NewConsumerWithClient(client KafkaConsumerClient, config *ConsumerConfig, logger Logger) Consumer
NewConsumerWithClient creates a new Kafka consumer with an injected client. This is primarily used for testing.
type ConsumerConfig ¶
type ConsumerConfig struct {
Brokers string
Username string
Password string
SecurityProtocol string
SASLMechanism string
CompressionCodec string
MessageTimeoutMs int
SocketTimeoutMs int
ClientID string
GroupID string
Topics []string
AutoOffsetReset string
PollTimeout time.Duration
AdditionalConfig map[string]string
}
ConsumerConfig holds configuration for creating a Kafka consumer.
func (*ConsumerConfig) ToConfigMap ¶
func (c *ConsumerConfig) ToConfigMap() *kafka.ConfigMap
ToConfigMap converts ConsumerConfig to kafka.ConfigMap.
func (*ConsumerConfig) Validate ¶
func (c *ConsumerConfig) Validate() error
Validate checks the required fields for ConsumerConfig.
type KafkaConsumerClient ¶
type KafkaConsumerClient interface {
SubscribeTopics(topics []string, rebalanceCb kafka.RebalanceCb) error
Poll(timeoutMs int) kafka.Event
CommitMessage(m *kafka.Message) ([]kafka.TopicPartition, error)
Close() error
}
KafkaConsumerClient is the interface that wraps the confluent kafka consumer methods we use. This enables injecting a mock kafka consumer for testing.
type KafkaProducerClient ¶
type KafkaProducerClient interface {
Produce(msg *kafka.Message, deliveryChan chan kafka.Event) error
Flush(timeoutMs int) int
Close()
Events() chan kafka.Event
}
KafkaProducerClient is the interface that wraps the confluent kafka producer methods we use. This enables injecting a mock kafka producer for testing.
type Logger ¶
type Logger interface {
// OnDeliverySuccess is called when a message is successfully delivered to Kafka.
OnDeliverySuccess(topic string, partition int32, offset kafka.Offset, key []byte)
// OnDeliveryFailed is called when a message delivery fails.
OnDeliveryFailed(topic string, key []byte, err error)
// OnProduceError is called when the producer fails to enqueue a message.
OnProduceError(topic string, key []byte, err error)
// OnError is called for general Kafka errors (producer or consumer).
OnError(component string, err kafka.Error)
// OnRebalance is called when consumer group rebalancing occurs.
OnRebalance(partitions []kafka.TopicPartition, assigned bool)
// OnConsume is called when a message is consumed.
OnConsume(topic string, partition int32, offset int64, key []byte)
// OnConsumeError is called when the message handler returns an error.
OnConsumeError(topic string, key []byte, err error)
// OnCommitSuccess is called when an offset commit succeeds.
OnCommitSuccess(topic string, partition int32, offset int64)
// OnCommitError is called when an offset commit fails.
OnCommitError(topic string, partition int32, offset int64, err error)
// OnLog is called for general Kafka log messages.
OnLog(level int, facility string, message string)
}
Logger defines callback/logging interface for Kafka events. Implement this interface to integrate with your application's logging system. This replaces the static KafkaCallable pattern from PHP with a testable interface.
type Message ¶
type Message struct {
Topic string
Partition int32
Offset int64
Key []byte
Value []byte
Headers []Header
Timestamp time.Time
}
Message represents a consumed Kafka message.
type MessageHandler ¶
MessageHandler is a function that processes a consumed Kafka message. Return nil to acknowledge the message, or return an error to signal failure.
type NopLogger ¶
type NopLogger struct{}
NopLogger is a no-op logger implementation that discards all log events. Useful for testing when you don't want log output.
func (*NopLogger) OnCommitError ¶
func (*NopLogger) OnCommitSuccess ¶
func (*NopLogger) OnConsumeError ¶
func (*NopLogger) OnDeliveryFailed ¶
func (*NopLogger) OnDeliverySuccess ¶
func (*NopLogger) OnProduceError ¶
func (*NopLogger) OnRebalance ¶
func (l *NopLogger) OnRebalance(partitions []kafka.TopicPartition, assigned bool)
type Producer ¶
type Producer interface {
// Publish sends a message to the specified topic.
Publish(ctx context.Context, topic string, key []byte, value []byte, headers []Header) error
// PublishWithPartition sends a message to a specific partition of the topic.
PublishWithPartition(ctx context.Context, topic string, partition int32, key []byte, value []byte, headers []Header) error
// Flush waits for all outstanding produce requests to complete.
Flush(timeoutMs int) int
// Close gracefully shuts down the producer.
Close()
}
Producer defines the interface for publishing messages to Kafka. This interface enables mocking in unit tests.
func NewProducer ¶
func NewProducer(config *ProducerConfig, logger Logger) (Producer, error)
NewProducer creates a new Kafka producer instance.
func NewProducerWithClient ¶
func NewProducerWithClient(client KafkaProducerClient, config *ProducerConfig, logger Logger) Producer
NewProducerWithClient creates a new Kafka producer with an injected client. This is primarily used for testing.
type ProducerConfig ¶
type ProducerConfig struct {
Brokers string
Username string
Password string
SecurityProtocol string
SASLMechanism string
CompressionCodec string
MessageTimeoutMs int
SocketTimeoutMs int
AdditionalConfig map[string]string
}
ProducerConfig holds configuration for creating a Kafka producer.
func (*ProducerConfig) ToConfigMap ¶
func (c *ProducerConfig) ToConfigMap() *kafka.ConfigMap
ToConfigMap converts ProducerConfig to kafka.ConfigMap.
func (*ProducerConfig) Validate ¶
func (c *ProducerConfig) Validate() error
Validate checks the required fields for ProducerConfig.