go语言操作rabbitmq

go 复制代码
package main

import (
	"fmt"
	"log"
	"sync"
	"time"

	"github.com/streadway/amqp"
)

func declareQueue(ch *amqp.Channel, queueName string) error {
	_, err := ch.QueueDeclare(
		queueName, // name
		false,     // durable
		false,     // delete when unused
		false,     // exclusive
		false,     // no-wait
		nil,       // arguments
	)
	return err
}

func producer(ch *amqp.Channel, wg *sync.WaitGroup, queueName string) {
	defer wg.Done()

	for i := 1; i <= 5; i++ {
		message := fmt.Sprintf("Message %d", i)

		err := ch.Publish(
			"",        // exchange
			queueName, // routing key
			false,     // mandatory
			false,     // immediate
			amqp.Publishing{
				ContentType: "text/plain",
				Body:        []byte(message),
			})

		if err != nil {
			log.Fatalf("Failed to publish a message: %v", err)
		}

		fmt.Printf("Sent: %s\n", message)
		time.Sleep(time.Second)
	}
}

func consumer(ch *amqp.Channel, wg *sync.WaitGroup, queueName string) {
	defer wg.Done()

	msgs, err := ch.Consume(
		queueName, // queue
		"",        // consumer
		true,      // auto-ack
		false,     // exclusive
		false,     // no-local
		false,     // no-wait
		nil,       // args
	)

	if err != nil {
		log.Fatalf("Failed to register a consumer: %v", err)
	}

	for msg := range msgs {
		fmt.Printf("Received: %s\n", msg.Body)
	}
}

func main() {
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
		log.Fatalf("Failed to connect to RabbitMQ: %v", err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("Failed to open a channel: %v", err)
	}
	defer ch.Close()

	queueName := "your_queue_name"

	// Declare the queue before using it
	err = declareQueue(ch, queueName)
	if err != nil {
		log.Fatalf("Failed to declare queue: %v", err)
	}

	var wg sync.WaitGroup
	wg.Add(2)

	go producer(ch, &wg, queueName)
	go consumer(ch, &wg, queueName)

	wg.Wait()
}

运行结果

go 复制代码
Sent: Message 1    
Received: Message 1
Sent: Message 2
Received: Message 2
Sent: Message 3
Received: Message 3
Sent: Message 4
Received: Message 4
Sent: Message 5
Received: Message 5
相关推荐
007php0073 小时前
GoZero 上传文件File到阿里云 OSS 报错及优化方案
服务器·开发语言·数据库·python·阿里云·架构·golang
高 朗5 小时前
【GO基础学习】基础语法(2)切片slice
开发语言·学习·golang·slice
IT书架5 小时前
golang面试题
开发语言·后端·golang
醒过来摸鱼11 小时前
【Golang】协程
开发语言·后端·golang
灼华十一13 小时前
算法编程题-排序
数据结构·算法·golang·排序算法
bug_null13 小时前
RabbitMQ消息可靠性保证机制4--消费端限流
rabbitmq
宋发元13 小时前
Go语言使用 kafka-go 消费 Kafka 消息教程
golang·kafka·linq
青石路14 小时前
不依赖 Spring,你会如何自实现 RabbitMQ 消息的消费(一)
rabbitmq
宋发元14 小时前
Go消费kafka中kafkaReader.FetchMessage(ctx)和kafkaReader.ReadMessage(ctx)的区别
golang·kafka·linq
呼啦啦啦啦啦啦啦啦17 小时前
【Rabbitmq篇】RabbitMQ⾼级特性----持久性,发送⽅确认,重试机制
分布式·rabbitmq