gitee.com/h79/goutils@v1.22.10/mq/producer_ex.go (about)

     1  package mq
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"gitee.com/h79/goutils/common/logger"
     7  	"gitee.com/h79/goutils/common/result"
     8  	"github.com/apache/rocketmq-client-go/v2"
     9  	"github.com/apache/rocketmq-client-go/v2/primitive"
    10  	prod "github.com/apache/rocketmq-client-go/v2/producer"
    11  	"go.uber.org/zap"
    12  )
    13  
    14  var _ Producer = (*producerEx)(nil)
    15  
    16  type producerEx struct {
    17  	cfg      Config
    18  	producer rocketmq.Producer
    19  }
    20  
    21  func NewProducer(cfg Config) Producer {
    22  	return &producerEx{cfg: cfg}
    23  }
    24  
    25  func (rp *producerEx) Start() error {
    26  
    27  	p, e := rocketmq.NewProducer(
    28  		prod.WithNsResolver(primitive.NewPassthroughResolver([]string{rp.cfg.Client.Server})),
    29  		prod.WithRetry(rp.cfg.ProducerConf.Retry),
    30  		prod.WithQueueSelector(prod.NewManualQueueSelector()))
    31  	if e != nil {
    32  		return result.Errorf(result.ErrMqInitInternal, "[MQ] Init producer failed, error: %v", e).Log()
    33  	}
    34  
    35  	if e := p.Start(); e != nil {
    36  		return result.Errorf(result.ErrMqStartInternal, "[MQ] Start producer failed, error: %v", e).Log()
    37  	}
    38  	rp.producer = p
    39  	return nil
    40  }
    41  
    42  func (rp *producerEx) Stop() {
    43  	_ = rp.producer.Shutdown()
    44  }
    45  
    46  func (rp *producerEx) SendJson(topic string, event interface{}) error {
    47  	body, _ := json.Marshal(event)
    48  	return rp.SendBytes(topic, body)
    49  }
    50  
    51  func (rp *producerEx) SendBytes(topic string, data []byte) error {
    52  
    53  	logger.L().Debug("MQ",
    54  		zap.String("topic", topic),
    55  		zap.ByteString("data", data))
    56  	ctx := context.Background()
    57  	if _, err := rp.producer.SendSync(ctx, primitive.NewMessage(topic, data)); err != nil {
    58  		return result.Errorf(result.ErrMqPublishInternal, "MQ: Publish String topic(%s) failure, err= %+v", topic, err).Log()
    59  	}
    60  	return nil
    61  }
    62  
    63  func (rp *producerEx) SendAsync(topic string, data []byte) error {
    64  	logger.L().Debug("MQ",
    65  		zap.String("topic", topic),
    66  		zap.ByteString("data", data))
    67  	ctx := context.Background()
    68  	if err := rp.producer.SendAsync(ctx, func(ctx context.Context, result *primitive.SendResult, err error) {
    69  
    70  	}, primitive.NewMessage(topic, data)); err != nil {
    71  		return result.Errorf(result.ErrMqPublishInternal, "MQ: Publish String topic(%s) failure, err= %+v", topic, err).Log()
    72  	}
    73  	return nil
    74  }