feat 初始化
This commit is contained in:
@@ -3,26 +3,39 @@ package kafka
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/IBM/sarama"
|
||||
"go.opentelemetry.io/otel"
|
||||
otelcodes "go.opentelemetry.io/otel/codes"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func NewProducer() *Producer {
|
||||
return &Producer{}
|
||||
var ProduceTimeoutError = errors.New("kafka producer timeout")
|
||||
|
||||
func NewProducer(key int64) *Producer {
|
||||
return &Producer{
|
||||
key: key,
|
||||
}
|
||||
}
|
||||
|
||||
type Producer struct {
|
||||
key int64
|
||||
}
|
||||
|
||||
func (c *Producer) Produce(ctx context.Context, data Topic) {
|
||||
func (c *Producer) Produce(ctx context.Context, data Topic) error {
|
||||
marshal, _ := json.Marshal(data)
|
||||
msg := &sarama.ProducerMessage{
|
||||
Topic: data.Name(),
|
||||
Key: sarama.StringEncoder(strconv.FormatInt(c.key, 10)),
|
||||
Value: sarama.ByteEncoder(marshal),
|
||||
Headers: NewCarrier().Inject(ctx),
|
||||
}
|
||||
client.producer.Input() <- msg
|
||||
select {
|
||||
case client.producer.Input() <- msg:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ProduceTimeoutError
|
||||
}
|
||||
}
|
||||
|
||||
func producerError() {
|
||||
|
||||
Reference in New Issue
Block a user