go 连MQ

go 连MQ

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/apache/rocketmq-client-go/v2"
	"github.com/apache/rocketmq-client-go/v2/primitive"
	"github.com/apache/rocketmq-client-go/v2/producer"
)

func main() {
	p, err := rocketmq.NewProducer(
		producer.WithNameServer([]string{"192.168.20.222:9876", "192.168.18.236:9876"}),
	)
	if err != nil {
		panic(err)
	}
	err = p.Start()
	defer func() {
		err = p.Shutdown()
		if err != nil {
			fmt.Printf("shutdown producer error: %s", err.Error())
		}
	}()
	if err != nil {
		fmt.Printf("start producer error: %s", err.Error())
		os.Exit(1)
	}
	msg := &primitive.Message{
		Topic: "xxxx",   # MQ topic名字
		Body:  []byte("Hello RocketMQ Go Client!"),
	}
	res, err := p.SendSync(context.Background(), msg)
	if err != nil {
		panic(err)
	}
	fmt.Println("发送成功,result:", res.String())
}

posted @ 2024-10-25 18:01  taotaozh  阅读(3)  评论(0编辑  收藏  举报