GO 并发生产消息示例

GO 并发生产消息示例

模拟环境 :

TCP 连接池 2000,并发 50000,总计生产 50万条消息数据 :

package main

import (
	"fmt"
	"runtime"
	"strconv"
	"sync"
	"time"

	"github.com/cnlesscode/graceMessageQueueClient/client"
)

// 全局变量
var addr string = "192.168.1.100:8881"
var graceMQConnetionPool *client.GraceMQConnectionPool
var wg sync.WaitGroup

func main() {
	// 观察协程
	go func() {
		for {
			fmt.Printf("协程数 : %v\n", runtime.NumGoroutine())
			time.Sleep(time.Second * 3)
		}
	}()
	// 初始化连接池
	graceMQConnetionPool = client.Init(addr, 2000)
	doTime := 1
productMessage:
	for i := 1; i <= 50000; i++ {
		wg.Add(1)
		go func(step int) {
			defer wg.Done()
			// 生产消息
			res := graceMQConnetionPool.ProductMessage(
				"topic2",
				strconv.Itoa(step)+"message data")
			if res.Errcode != 0 {
				fmt.Printf("res.Data: %v\n", res.Data)
			}
		}(i)
	}
	wg.Wait()
	doTime += 1
	fmt.Printf("doTime: %v\n", doTime)
	if doTime <= 10 {
		goto productMessage
	}
	println("--- main done ---")
}