美文网首页rabbitmq with golang我爱编程
golang写第一个rabbitmq程序

golang写第一个rabbitmq程序

作者: 百味纯净水 | 来源:发表于2018-06-18 01:46 被阅读456次

    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()
    }
    

    相关文章

      网友评论

        本文标题:golang写第一个rabbitmq程序

        本文链接:https://www.haomeiwen.com/subject/fxvgeftx.html