RocketMQ开启ACL认证Go连接测试
RocketMQ开启ACL认证连接测试
导入包
go get -u github.com/apache/rocketmq-client-go/v2
go get -u github.com/spf13/pflag
查看go.mod
module your_module_name
go 1.16
require (
github.com/apache/rocketmq-client-go/v2 v2.1.0
github.com/spf13/pflag v1.0.5
)
测试代码:
package main
import (
"context"
"flag"
"fmt"
"os"
"time"
"github.com/apache/rocketmq-client-go/v2"
"github.com/apache/rocketmq-client-go/v2/consumer"
"github.com/apache/rocketmq-client-go/v2/primitive"
"github.com/apache/rocketmq-client-go/v2/producer"
)
func main() {
// 定义命令行参数
namesrvAddr := flag.String("n", "127.0.0.1:9876", "NameServer address")
accessKey := flag.String("a", "", "Access Key for ACL authentication")
secretKey := flag.String("s", "", "Secret Key for ACL authentication")
topic := flag.String("t", "test-topic", "Topic for sending and receiving messages")
help := flag.Bool("h", false, "Display help information")
// 解析命令行参数
flag.Parse()
// 如果用户请求帮助信息
if *help {
flag.Usage()
os.Exit(0)
}
// 验证必需的参数
if *accessKey == "" || *secretKey == "" {
fmt.Println("Error: accessKey and secretKey are required.")
flag.Usage()
os.Exit(1)
}
testRocketMQConnection(*namesrvAddr, *accessKey, *secretKey, *topic)
}
func testRocketMQConnection(namesrvAddr, accessKey, secretKey, topic string) {
// 创建生产者
p, err := rocketmq.NewProducer(
producer.WithNameServer([]string{namesrvAddr}),
producer.WithCredentials(primitive.Credentials{
AccessKey: accessKey,
SecretKey: secretKey,
}),
)
if err != nil {
fmt.Printf("创建生产者失败:%s\n", err)
os.Exit(1)
}
err = p.Start()
if err != nil {
fmt.Printf("启动生产者失败:%s\n", err)
os.Exit(1)
}
defer p.Shutdown()
// 发送一条消息
msg := &primitive.Message{
Topic: topic,
Body: []byte("Hello RocketMQ!"),
}
res, err := p.SendSync(context.Background(), msg)
if err != nil {
fmt.Printf("发送消息失败:%s\n", err)
os.Exit(1)
}
fmt.Printf("发送结果:%s\n", res.String())
// 创建消费者
c, err := rocketmq.NewPushConsumer(
consumer.WithNameServer([]string{namesrvAddr}),
consumer.WithCredentials(primitive.Credentials{
AccessKey: accessKey,
SecretKey: secretKey,
}),
)
if err != nil {
fmt.Printf("创建消费者失败:%s\n", err)
os.Exit(1)
}
err = c.Subscribe(topic, consumer.MessageSelector{}, func(ctx context.Context,
msgs ...*primitive.MessageExt) (consumer.ConsumeResult, error) {
fmt.Printf("接收到消息:%s\n", msgs[0].MsgId)
return consumer.ConsumeSuccess, nil
})
if err != nil {
fmt.Printf("订阅主题失败:%s\n", err)
os.Exit(1)
}
err = c.Start()
if err != nil {
fmt.Printf("启动消费者失败:%s\n", err)
os.Exit(1)
}
defer c.Shutdown()
// 等待消费者接收消息
time.Sleep(5 * time.Second)
}
go build成为可执行二进制文件,在执行测试命令
./your-binary-name -n "127.0.0.1:9876" -a "your-access-key" -secretKe "your-secret-key" -t "test-topic"
-h可查看帮助
./your-binary-name -h