golang使用rabbitMQ入门代码
package main import ( "github.com/streadway/amqp" "log" "time" ) func main() { go sendMessagePreSecond() receive() } func sendMessagePreSecond() { for { send() time.Sleep(1 * time.Second) } } func send() { conn, err := amqp.Dial("amqp://hsn:qwer1234@192.168.147.132/") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() queue, e := ch.QueueDeclare("test_queue", false, false, false, false, nil) failOnError(e, "Failed to declare a queue") body := "hello world!" err = ch.Publish("", queue.Name, false, false, amqp.Publishing{ ContentType: "text/plain", Body: []byte(body), }) failOnError(err, "Failed to publish a message") log.Println("send") } func receive() { conn, err := amqp.Dial("amqp://hsn:qwer1234@192.168.147.132/") failOnError(err, "Failed to connect to RabbitMQ") defer conn.Close() ch, err := conn.Channel() failOnError(err, "Failed to open a channel") defer ch.Close() queue, err := ch.QueueDeclare("test_queue", false, false, false, false, nil) failOnError(err, "Failed to declare queue") msgCh, err := ch.Consume(queue.Name, "", true, false, false, false, nil) failOnError(err, "Failed to receive message") forever := make(chan bool) go func() { for d := range msgCh { log.Println("message: ", string(d.Body)) } }() log.Printf(" [*] Waiting for messages. To exit press CTRL+C") <-forever } func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } }