transfer_middleware/cmd/rpc/pkg/mq/rocketmq.go

40 lines
1.0 KiB
Go

package mq
import (
"context"
"encoding/json"
"fmt"
"github.com/apache/rocketmq-client-go/v2"
"github.com/apache/rocketmq-client-go/v2/primitive"
"github.com/apache/rocketmq-client-go/v2/producer"
)
type RocketMq struct {
}
func (n RocketMq) Produce(host []string, groupName string, topic string, log interface{}, delayTime int) (string, error) {
p, err := rocketmq.NewProducer(
producer.WithNsResolver(primitive.NewPassthroughResolver(host)),
producer.WithRetry(2), //指定重试次数
producer.WithGroupName(groupName),
)
defer p.Shutdown()
if err != nil {
return "", fmt.Errorf("rockmq error:%v", err)
}
if err = p.Start(); err != nil {
return "", fmt.Errorf("rockmq error:%v", err)
}
var body, _ = json.Marshal(log)
// 构建一个消息
message := primitive.NewMessage(topic, body)
// 给message设置延迟级别
message.WithDelayTimeLevel(delayTime)
res, err := p.SendSync(context.Background(), message)
if err != nil {
fmt.Errorf("rockmq send message fail:%v", err)
}
return res.String(), nil
}