package main import ( "fmt" "github.com/streadway/amqp" "log" "time" ) func failOnError(err error, msg string) { if err != nil { log.Fatalf("%s: %s", msg, err) } } func xiaofei(name string) { dial, err := amqp.Dial("amqp://guest:guest@192.168.1.187:5673/") failOnError(err, "链接失败") channel, err := dial.Channel() failOnError(err, "channel链接失败") defer channel.Close() declare, err := channel.QueueDeclare( "task_queue", true, false, false, false, nil, ) failOnError(err, "Failed to declare a queue") err = channel.Qos( 1, // prefetch count 0, // prefetch size false, // global ) failOnError(err, "Failed to set QoS") msgs, err := channel.Consume( declare.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 { fmt.Println("内容", string(d.Body), "协成", name) d.Ack(false) } }() <-forever } // channel 练习 func main() { go xiaofei("1") go xiaofei("2") dial, err := amqp.Dial("amqp://guest:guest@192.168.1.187:5673/") failOnError(err, "链接失败") channel, err := dial.Channel() failOnError(err, "channel链接失败") defer channel.Close() declare, err := channel.QueueDeclare( "task_queue", true, false, false, false, nil, ) failOnError(err, "创建队列错误") for i := 0; i < 50; i++ { body := fmt.Sprintln("信息", i) channel.Publish("", declare.Name, false, false, amqp.Publishing{DeliveryMode: amqp.Persistent, ContentType: "text/plain", Body: []byte(body)}) failOnError(err, "Failed to publish a message") } time.Sleep(10 * time.Second) }