Home >Backend Development >Golang >How Can I Implement Timeouts for RPC Calls?

How Can I Implement Timeouts for RPC Calls?

DDD
DDDOriginal
2024-10-29 18:11:18389browse

 How Can I Implement Timeouts for RPC Calls?

Can RPC call requests be timed out?

RPC, or Remote Procedure Call, is a mechanism for calling functions in a different process, but due to network latencies or other issues, calls can sometimes get stuck.

If RPC does not have a built-in timeout mechanism, such situations can be handled by using channels to implement a timeout pattern:

import "time"

c := make(chan error, 1)
go func() { c <- client.Call("Service", args, &result) } ()
select {
  case err := <-c:
    // use err and result
  case <-time.After(timeoutNanoseconds):
    // call timed out
}

In this example:

  • c is a channel that can hold a maximum of one error.
  • A goroutine executes the RPC call and sends the error (or result) to the channel.
  • The select statement blocks until either the goroutine finishes executing and sends the channel the error, or the timeoutNanoseconds elapses. If the former happens, the execution continues with the err and result variables, while in the latter case the operation times out.

The above is the detailed content of How Can I Implement Timeouts for RPC Calls?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn