golang写第一个rabbitmq程序

1.介绍

使用amqp的库用golang语言进行rabbitmq的开发,此文章的代码可以用来安装完成rabbitmq后,进行测试。也可以作为学习rabbitmq的第一个测试程序。

2.golang rabbitmq库地址

https://github.com/streadway/amqp

3.错误处理

func failOnErr(err error, msg string) {
    if err != nil {
        fmt.Println("msg", err, msg)
        panic("error")
    }
}

4. 建立连接

func mqConnect() {
    var err error
    conn, err = amqp.Dial(mqurl)
    failOnErr(err, "connect")

    channel , err = conn.Channel()
    failOnErr(err, "channel")
}

5.断开连接

func close(){
    channel.Close()
    conn.Close()
}

6.声明交换器、消息队列并发送消息

func push() {
    if channel == nil {
        mqConnect()
    }

    mgsConnect := "hello world"
    err := channel.ExchangeDeclare(exchange, "direct", false, false, false,false, nil)
    failOnErr(err, "ExchangeDeclare")

    _, err = channel.QueueDeclare(queueName, false, false,
        false, false, nil)
    failOnErr(err, "QueueDeclare")

    err = channel.QueueBind(queueName, "info", exchange, false, nil)
    failOnErr(err, "QueueBind")

    err = channel.Publish(exchange, "info", false, false, amqp.Publishing{
        ContentType:"text/plain", Body:[]byte(mgsConnect),
    })
    failOnErr(err, "Publish")

    fmt.Println("push ok")
}

.7消费消息

func receive() {
    if channel == nil {
        mqConnect()
    }

    msg, ok, err := channel.Get(queueName, false)
    failOnErr(err, "")
    if !ok {
        fmt.Println("do not get msg")
        return
    }

    err = channel.Ack(msg.DeliveryTag, false)
    failOnErr(err, "")

    s := BytesToString(&(msg.Body))
    fmt.Printf("receve msg is :%s\n", *s)
}

func BytesToString(b *[]byte) *string {
    s := bytes.NewBuffer(*b)
    r := s.String()
    return &r
}

.8程序入口

package main

import (
    "github.com/streadway/amqp"
    "fmt"
    "bytes"
)

var conn *amqp.Connection
var channel *amqp.Channel

const (
    queueName = "hello"
    exchange = "exchange1"
    mqurl = "amqp://username:password@localhost:5672/"
)

func main() {
    push()
    receive()
    fmt.Println("end")
    close()
}
    原文作者:苏云龙
    原文地址: https://www.jianshu.com/p/eb1ba1fdb6dd
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞