rabbitmq操作(go)

75 阅读1分钟

1、定义option结构体,用户初始化参数

package rabbimqGo

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
	"sync"
)

type Option struct {
	User string
	Passwd string
	Host  string
	Port   string
	Vhost  string

}
type MQoption func(o *Option)

2、链接等操作

//链接rabbitmq
func NewRbtMQ(mq MQoption) *amqp.Connection {
	option:=Option{
		Port:   "5672",
		Vhost:  "",
	}

	mq(&option)

	url:=fmt.Sprintf("amqp://%s:%s@%s:%s/%s",option.User,option.Passwd,option.Host,option.Port,option.Vhost)
	conn,err := amqp.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	return conn

}
//创建队列
func QueueCreate(c *amqp.Channel,name string) *amqp.Queue{
	q,e:=c.QueueDeclare(
			"hello", // name
			false,   // durable
			false,   // delete when unused
			false,   // exclusive
			false,   // no-wait
			nil,
	)
	if e!=nil{
		panic(e)
	}
	return &q
}

//生产消息
func PublicMs(c *amqp.Channel,q *amqp.Queue,message string){
	e:=c.Publish(
		"",
		(*q).Name,
		false,
		false,
		amqp.Publishing{
			ContentType: "text/plain",
			Body:        []byte(message),
			},
		)
	if e!=nil{
		panic(e)
	}
	fmt.Printf("【***】发送消息:%s success!\n",message)
}
// 消费消息
func RevMessage(wg *sync.WaitGroup, c *amqp.Channel,q *amqp.Queue){
	defer wg.Done()
	msgs, err := c.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
		)

	if err!=nil{
		panic(err)
	}

	select{
		case d:=<-msgs:
			fmt.Printf("【---】接受到的消息: %s!\n", d.Body)
	}


}