The use of golang rabbitmq

Keywords: Go github RabbitMQ

golang can use the library github.com/streadway/amqp to operate rabbitmq

install

go get github.com/streadway/amqp

Connect

conn, err := amqp.Dial(amqp://guest:guest@172.17.84.205:5672/)

Establishing channels

ch, err := conn.Channel()

Statement Queue

q, err := ch.QueueDeclare(
                "testqueue", //Queue name
                true, //durable
                false,
                false,
                false,
                nil,
            )

If durable is set to true, the queue will be persisted, otherwise it will not be persisted.

Publish news

err = ch.Publish(
                "",     //exchange
                q.Name, //routing key(queue name)
                false,
                false,
                amqp.Publishing{
                    DeliveryMode: amqp.Persistent, //Msg set as persistent
                    ContentType:  "text/plain",
                    Body:         []byte(msgBody),
                })

If the DeliveryMode of amqp.Publishing is set to amqp.Persistent, the message will be persisted.
It should be noted that if message persistence is required, Queue also needs to be set as persistence to be effective

receive messages

msgs, err := ch.Consume(
                q.Name,
                "MsgWorkConsumer",
                false,  //Auto Ack
                false,
                false,
                false,
                nil,
            )

Where Auto ack can be set to true. If it is set to true, the consumer will be removed from the queue as soon as it is received, and the message will be lost if there is an accident in the consumer's processing message.
If Auto ack is set to false. After consumer finishes processing the message, the message is removed from the queue after calling msg.Ack(false). Even if the current consumer handles the message unexpectedly, as long as msg.Ack(false) is not executed, the message is still in the queue and will not be lost.

The generated Queue is a set parameter in generation. The set parameter cannot be changed in the next use, otherwise an error will be reported

The example code is as follows
conf.go

package config

const (
    RMQADDR     = "amqp://guest:guest@172.17.84.205:5672/"
    QUEUENAME   = "msgQueueWithPersist"
    PRODUCERCNT = 5
    CONSUMERCNT = 20
)

producer.go

package main

import (
    config "xxx/conf"
    "fmt"
    "log"
    "sync"

    "github.com/streadway/amqp"
)

func main() {

    conn, err := amqp.Dial(config.RMQADDR)
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    var wg sync.WaitGroup
    wg.Add(config.PRODUCERCNT)

    for routine := 0; routine < config.PRODUCERCNT; routine++ {
        go func(routineNum int) {
            ch, err := conn.Channel()
            failOnError(err, "Failed to open a channel")
            defer ch.Close()

            q, err := ch.QueueDeclare(
                config.QUEUENAME, //Queue name
                true, //durable
                false,
                false,
                false,
                nil,
            )

            failOnError(err, "Failed to declare a queue")

            for i := 0; i < 500; i++ {
                msgBody := fmt.Sprintf("Message_%d_%d", routineNum, i)

                err = ch.Publish(
                    "",     //exchange
                    q.Name, //routing key
                    false,
                    false,
                    amqp.Publishing{
                        DeliveryMode: amqp.Persistent, //Msg set as persistent
                        ContentType:  "text/plain",
                        Body:         []byte(msgBody),
                    })

                log.Printf(" [x] Sent %s", msgBody)
                failOnError(err, "Failed to publish a message")
            }

            wg.Done()
        }(routine)
    }

    wg.Wait()

    log.Println("All messages sent!!!!")
}

func failOnError(err error, msg string) {
    if err != nil {
        fmt.Printf("%s: %s\n", msg, err)
    }
}

consumer.go

package main

import (
    config "xxx/conf"
    "fmt"
    "log"

    "github.com/streadway/amqp"
)

func main() {

    conn, err := amqp.Dial(config.RMQADDR)
    failOnError(err, "Failed to connect to RabbitMQ")
    defer conn.Close()

    forever := make(chan bool)

    for routine := 0; routine < config.CONSUMERCNT; routine++ {
        go func(routineNum int) {
            ch, err := conn.Channel()
            failOnError(err, "Failed to open a channel")
            defer ch.Close()

            q, err := ch.QueueDeclare(
                config.QUEUENAME,
                true, //durable
                false,
                false,
                false,
                nil,
            )

            failOnError(err, "Failed to declare a queue")

            msgs, err := ch.Consume(
                q.Name,
                "MsgWorkConsumer",
                false,  //Auto Ack
                false,
                false,
                false,
                nil,
            )

            if err != nil {
                log.Fatal(err)
            }

            for msg := range msgs {
                log.Printf("In %d consume a message: %s\n", 0, msg.Body)
                log.Printf("Done")
                msg.Ack(false) //Ack
            }

        }(routine)
    }

    <-forever
}

func failOnError(err error, msg string) {
    if err != nil {
        fmt.Printf("%s: %s\n", msg, err)
    }
}

The full sample code is in
https://github.com/BinWang-sh...

Posted by black.horizons on Fri, 15 Nov 2019 06:12:49 -0800