The request-reply pattern

In this pattern, Service-A (requestor) wants some work from from Service-B (responder), and there is output expected out of the request. How does Service-B respond, considering that Service-B might be handling requests for a lot of other services?

The solution is to have the requestor mention the response topic (in this case, the channel) to the responder. This decouples the responder from requestor. A request message might look like this:

type Request struct { 
   someArg string 
   replyTo chan<- Response 
} 
 
type Response struct { 
   reply string 
} 

Notice the replyTo channel that the requester is sending along with the message.

The requestor and responder code looks like the following:

func responder(c <-chan Request) { 
   for request := range c { 
         var resp Response 
         resp.reply = "reply-to-" + request.someArg 
         request.replyTo <- resp 
   } 
} 
 
func requestor(c chan<- Request) { 
   myChannel := make(chan Response) 
   for i := 0; i < 5; i++ { 
         c <- Request{fmt.Sprintf("message%d", i), myChannel} 
         resp := <-myChannel 
         fmt.Printf("request %d, response %s
", i, resp.reply) 
   } 
 
   // cleanup after my work is done 
   close(myChannel) 
} 
 
func main() { 
 
   requestChannel := make(chan Request) 
   go responder(requestChannel) 
   go requestor(requestChannel) 
 
   time.Sleep(time.Second * 10) 
 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset