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
相关推荐
P.H. Infinity4 小时前
【RabbitMQ】03-交换机
分布式·rabbitmq
qq_1728055912 小时前
GIN 反向代理功能
后端·golang·go
__AtYou__12 小时前
Golang | Leetcode Golang题解之第535题TinyURL的加密与解密
leetcode·golang·题解
孤蓬&听雨12 小时前
RabbitMQ自动发送消息工具(自动化测试RabbitMQ)
分布式·测试工具·自动化·rabbitmq·自动发送消息
呼啦啦啦啦啦啦啦啦12 小时前
RabbitMQ 七种工作模式介绍
分布式·rabbitmq
qq_2037694912 小时前
win11安装最新rabbitmq
分布式·rabbitmq·ruby
Amagi.12 小时前
RabbitMQ的解耦、异步、削峰是什么?
分布式·rabbitmq
kevin_tech17 小时前
Go API 多种响应的规范化处理和简化策略
开发语言·后端·golang·状态模式
小码哥呀18 小时前
RabbitMQ设置消息过期时间
分布式·rabbitmq
斑驳竹影18 小时前
rabbitMQ RabbitTemplate 发送消息
java·rabbitmq·java-rabbitmq