https://github.com/streadway/amqp
package main
import (
"fmt"
"log"
"test1/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
fmt.Printf("%s: %s\n", msg, err)
}
}
func f6(){
conn, err := amqp.Dial("amqp://fm:[email protected]:5672/fm")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"", // name
false, // 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
true, // auto ack
false, // exclusive
false, // no local
false, // no wait
nil, // args
)
failOnError(err, "Failed to register a consumer")
body := "hello world!"
err = ch.Publish(
"", // exchange
"rpc_test", // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
CorrelationId: "32",
ReplyTo: q.Name,
Body: []byte(body),
})
log.Printf("send %s", body)
failOnError(err, "Failed to publish a message")
chfor := make( chan struct{})
go func() {
for d := range msgs {
log.Printf("client apply [%s] , %s", d.Body, d.CorrelationId)
}
}()
<-chfor //一直等待
}
func main(){
type pfun func()()
var apf pfun
apf = f6
apf()
fmt.Println("hello world")
}
package main
import (
"fmt"
"log"
"test1/amqp"
)
func failOnError(err error, msg string) {
if err != nil {
fmt.Printf("%s: %s\n", msg, err)
}
}
func f6(){
conn, err := amqp.Dial("amqp://fm:[email protected]:5672/fm")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()
ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()
q, err := ch.QueueDeclare(
"rpc_test", // name
false, // 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
true, // 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 client msg: [%s] ", d.Body)
err = ch.Publish(
"", // exchange
d.ReplyTo, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "text/plain",
CorrelationId: d.CorrelationId,
Body: []byte("server: reply"),
})
failOnError(err, "Failed to publish a message")
}
}()
log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
<-forever
}
func main(){
f6()
fmt.Println("hello world")
}