前言
需要包
go get github.com/apache/rocketmq-client-go/v2
1.簡單生產者
package main
import (
"context"
"fmt"
"github.com/apache/rocketmq-client-go/v2"
"github.com/apache/rocketmq-client-go/v2/primitive"
"github.com/apache/rocketmq-client-go/v2/producer"
"os"
"strconv"
)
func main() {
p, _ := rocketmq.NewProducer(
producer.WithNameServer([]string{"127.0.0.1:9876"}),
producer.WithRetry(2),
producer.WithGroupName("testGroup"),
)
err := p.Start()
if err != nil {
fmt.Printf("start producer error: %s", err.Error())
os.Exit(1)
}
topic := "Topic-test"
for i := 0; i < 10; i++ {
msg := &primitive.Message{
Topic: topic,
Body: []byte("Hello RocketMQ Go Client" + strconv.Itoa(i)),
}
res, err := p.SendSync(context.Background(),msg)
if err != nil {
fmt.Printf("send message error:%s\n",err)
}else {
fmt.Printf("send message success: result=%s\n",res.String())
}
}
err = p.Shutdown()
if err != nil {
fmt.Printf("shutdown producer error:%s",err.Error())
}
}
2.簡單消費者
package main
import (
"context"
"fmt"
"github.com/apache/rocketmq-client-go/v2"
"github.com/apache/rocketmq-client-go/v2/consumer"
"github.com/apache/rocketmq-client-go/v2/primitive"
"os"
"time"
)
func main() {
c, _ := rocketmq.NewPushConsumer(
consumer.WithGroupName("testGroup"),
consumer.WithNameServer([]string{"127.0.0.1:9876"}),
)
err := c.Subscribe("Topic-test", consumer.MessageSelector{}, func(ctx context.Context, ext ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
for i := range ext {
fmt.Printf("subscribe callback:%v \n", ext[i])
}
return consumer.ConsumeSuccess, nil
})
if err != nil {
fmt.Println(err.Error())
}
err = c.Start()
if err != nil {
fmt.Println(err.Error())
os.Exit(-1)
}
time.Sleep(time.Hour)
err = c.Shutdown()
if err != nil {
fmt.Printf("shutdown Consumer error:%s",err.Error())
}
}
可能存在的問題
- 消費者先啟動,但是沒有建立 topic
- 可以設定rocketmq預設建立節點
- 可以通過admin 建立節點 參考地址
結語
本作品採用《CC 協議》,轉載必須註明作者和本文連結