rabbitmq 简易RPC调用示例

rabbitmq 简易RPC调用示例(后附go代码))

    • rabbimq 库代码获取
    • 用例概述
    • 客户端
    • 服务端

rabbimq 库代码获取

https://github.com/streadway/amqp

用例概述

  1. 客户端
    客户端创建匿名队列q,并且从该队列获取消息(No wait return)
    客户端向消息队列rpc_test发送消息,消息中包含:
    CorrelationId: “32”,// 待服务端解析原样返回
    ReplyTo: q.Name, // 待服务端解析后将结果发送到指定队列,供客户端获取解析,根据CorrelationId做消息匹配
  2. 服务端
    服务端创建队列rpc_test,并且从该队列获取消息,
    收到消息后,解析客户端消息CorrelationId,ReplyTo(客户端要求将消息发送到该队列)
    服务将返回结果,和CorrelationId打包,返回到ReplyTo对应队列,供客户端解析使用

客户端

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")
}

你可能感兴趣的:(rabbitmq,golang)