Files
toutoukan/mq/killmq/producer/killProducer.go
JACKYMYPERSON c9d079b7f4 mq
2025-09-13 20:00:02 +08:00

66 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
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"
"log"
"time"
)
type OrderMessage struct {
OrderID string `json:"order_id"`
GoodsID int64 `json:"goods_id"`
UserID int64 `json:"user_id"`
Quantity int `json:"quantity"`
}
func main() {
// 1. 初始化普通消息生产者
normalProducer, err := rocketmq.NewProducer(
producer.WithNameServer([]string{"127.0.0.1:9876"}), // RocketMQ namesrv 地址
producer.WithGroupName("order_producer_group"), // 生产者组名
)
if err != nil {
log.Fatalf("初始化普通生产者失败: %v", err)
}
// 启动生产者
if err := normalProducer.Start(); err != nil {
log.Fatalf("启动普通生产者失败: %v", err)
}
defer normalProducer.Shutdown()
// 2. 发送普通消息示例
sendNormalMessage(normalProducer)
}
// 发送普通消息
func sendNormalMessage(p rocketmq.Producer) {
// 构造消息内容
msgData := OrderMessage{
OrderID: fmt.Sprintf("ORD%d", time.Now().UnixNano()),
GoodsID: 1001,
UserID: 10001,
Quantity: 1,
}
msgBody, _ := json.Marshal(msgData)
// 创建消息(指定主题和内容)
msg := primitive.NewMessage("killgoods", msgBody) // 主题需提前创建或开启自动创建
// 发送消息(同步发送,等待结果)
result, err := p.SendSync(context.Background(), msg)
if err != nil {
log.Printf("普通消息发送失败: %v", err)
return
}
log.Printf("普通消息发送成功消息ID: %s, 队列: %d, 偏移量: %d",
result.MsgID, result.MessageQueue.QueueId, result.QueueOffset)
}