golang操作rocketmq

  1. 下载
    go get github.com/apache/rocketmq-client-go/v2

  2. 代码

func main() {
	// 1. 创建主题
	//CreateTopic("test-04", 10909)

	// 2. 生产者向主题中发送消息
	//SendSyncMessage("hello world0002")

	// 3. 消费者订阅主题并消费
	go SubscribeMessage()
	time.Sleep(time.Second * 5)
	SendSyncMessage("hello world0003")
	time.Sleep(time.Second * 5)
	SendSyncMessage("hello world0004")
	time.Sleep(time.Second * 20)

}

func CreateTopic(topicName string, port int) {
	// 创建主题
	testAdmin, err := admin.NewAdmin(admin.WithResolver(primitive.NewPassthroughResolver([]string{"ip:server_port"})))
	if err != nil {
		fmt.Println(err)
	}
	err = testAdmin.CreateTopic(
		context.Background(),
		admin.WithTopicCreate(topicName),
		admin.WithBrokerAddrCreate(fmt.Sprintf("ip:%d", port)),
	)
	fmt.Println(err)
}

func SendSyncMessage(message string) {
	endPoint := []string{"ip:server_port"}
	p, err := rocketmq.NewProducer(
		producer.WithNameServer(endPoint),
		//producer.WithNsResolver(primitive.NewPassthroughResolver(endPoint)),
		producer.WithRetry(2),
	)
	if err != nil {
		fmt.Println(err)
	}

	err = p.Start()
	if err != nil {
		fmt.Println(err)
	}

	result, err := p.SendSync(context.Background(), &primitive.Message{
		Topic: "test",
		Body:  []byte(message),
	})
	fmt.Println(result.Status, result)

}

func SubscribeMessage() {
	// 订阅主题、并消费
	endPoint := []string{"ip:server_port"}
	c, err := rocketmq.NewPushConsumer(
		consumer.WithNameServer(endPoint),
		consumer.WithConsumerModel(consumer.Clustering),
		consumer.WithGroupName("GID_TEST01"),
	)
	if err != nil {
		//fmt.Println(err)
	}

	err = c.Subscribe("test", consumer.MessageSelector{}, func(ctx context.Context,
		msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
		for i := range msgs {
			fmt.Printf("subscribe callback: %v \n", msgs[i])
		}

		return consumer.ConsumeSuccess, nil
	})
	if err != nil {
		//fmt.Println(err.Error())
	}
	// Note: start after subscribe
	err = c.Start()
	c.Shutdown()
	select {

	}
	if err != nil {
		//fmt.Println(err.Error())
		os.Exit(-1)
	}
}

参考文档

posted @ 2022-04-06 13:47  专职  阅读(557)  评论(0编辑  收藏  举报