golang rabbitmq 简单模式

package main

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

func failOnError(err error, msg string) {
    if err != nil {
        log.Fatalf("%s: %s", msg, err)
    }
}

func getConn() *amqp.Connection {
    conn, err := amqp.Dial("amqp://guest:guest@192.168.1.187:5673/")
    failOnError(err, "Failed to connect to RabbitMQ")
    return conn
}

func push(message string) {
    conn := getConn()
    defer conn.Close()
    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()
    q, err := ch.QueueDeclare(
        "cheng1", // name
        true,     // durable
        false,    // delete when unused
        false,    // exclusive
        false,    // no-wait
        nil,      // arguments
    )
    failOnError(err, "Failed to declare a queue")
    body := message
    err = ch.Publish(
        "",     // exchange
        q.Name, // routing key
        false,  // mandatory
        false,  // immediate
        amqp.Publishing{
            ContentType: "text/plain",
            Body:        []byte(body),
        })
    failOnError(err, "Failed to publish a message")
    fmt.Println(message)
}

func send() {
    conn := getConn()
    defer conn.Close()
    ch, err := conn.Channel()
    failOnError(err, "Failed to open a channel")
    defer ch.Close()
    q, err := ch.QueueDeclare(
        "cheng1", // name
        true,     // durable
        false,    // delete when unused
        false,    // exclusive
        false,    // no-wait
        nil,      // arguments
    )
    failOnError(err, "Failed to declare a queue")
    msgs, err := ch.Consume(
        q.Name, // queue
        "",     // consumer
        false,  // auto-ack
        false,  // exclusive
        false,  // no-local
        false,  // no-wait
        nil,    // args
    )
    failOnError(err, "Failed to register a consumer")

    forever := make(chan bool)

    go func() {
        for d := range msgs {
            log.Printf("Received a message: %s", d.Body)
            fmt.Println(d.DeliveryTag)
            d.Ack(true)
        }
    }()

    log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
    <-forever
}

func main() {
    bools := make(chan bool)
    go send()
    //go func() {
    //    for i := 0; i < 1000000; i++ {
    //        push(strconv.Itoa(i))
    //    }
    //}()
    <-bools
}

 

posted @ 2022-06-02 14:47  酷酷的城池  阅读(26)  评论(0编辑  收藏  举报