【Go语言】Go的RPC包是Synchronous call还是Asynchronous call?

本文详细介绍了RPC(Remote Procedure Call)的工作原理,包括客户端和服务器端的交互过程。服务器通过注册对象使其作为服务可见,客户端通过连接调用服务。RPC调用必须满足特定条件,如方法参数和返回类型。文章还展示了简单的服务注册和调用示例,以及RPC错误处理。同时,提到了`net/rpc`包的一些内部结构,如Request和Response类型,以及ServerCodec接口。
摘要由CSDN通过智能技术生成

Package rpc provides access to the exported methods of an object across a network or other I/O connection.

A server registers an object, making it visible as a service with the name of the type of the object. After registration, exported methods of the object will be accessible remotely. A server may register multiple objects (services) of different types but it is an error to register multiple objects of the same type.

Only methods that satisfy these criteria will be made available for remote access; other methods will be ignored:

  • the method’s type is exported.
  • the method is exported.
  • the method has two arguments, both exported (or builtin) types.
  • the method’s second argument is a pointer.
  • the method has return type error.

In effect, the method must look schematically like

func (t *T) MethodName(argType T1, replyType *T2) error

where T1 and T2 can be marshaled by encoding/gob. These requirements apply even if a different codec is used. (In the future, these requirements may soften for custom codecs.)

  • The method’s first argument represents the arguments provided by the caller;
  • The second argument represents the result parameters to be returned to the caller.
  • The method’s return value, if non-nil, is passed back as a string that the client sees as if created by errors.New. If an error is returned, the reply parameter will not be sent back to the client.

The server may handle requests on a single connection by calling ServeConn. More typically it will create a network listener and call Accept or, for an HTTP listener, HandleHTTP and http.Serve.

A client wishing to use the service establishes a connection and then invokes NewClient on the connection. The convenience function Dial (DialHTTP) performs both steps for a raw network connection (an HTTP connection). The resulting Client object has two methods, Call and Go, that specify the service and method to call, a pointer containing the arguments, and a pointer to receive the result parameters.

  • The Call method waits for the remote call to complete
  • The Go method launches the call asynchronously and signals completion using the Call structure’s Done channel.

Unless an explicit codec is set up, package encoding/gob is used to transport the data.

Here is a simple example. A server wishes to export an object of type Arith:

package server

import "errors"

type Args struct {
	A, B int
}

type Quotient struct {
	Quo, Rem int
}

type Arith int

func (t *Arith) Multiply(args *Args, reply *int) error {
	*reply = args.A * args.B
	return nil
}

func (t *Arith) Divide(args *Args, quo *Quotient) error {
	if args.B == 0 {
		return errors.New("divide by zero")
	}
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return nil
}

The server calls (for HTTP service):

arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
	log.Fatal("listen error:", e)
}
go http.Serve(l, nil)

At this point, clients can see a service “Arith” with methods “Arith.Multiply” and “Arith.Divide”. To invoke one, a client first dials the server:

client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
if err != nil {
	log.Fatal("dialing:", err)
}

Then it can make a remote call:

// Synchronous call
args := &server.Args{7,8}
var reply int
err = client.Call("Arith.Multiply", args, &reply)
if err != nil {
	log.Fatal("arith error:", err)
}
fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)

or

// Asynchronous call
quotient := new(Quotient)
divCall := client.Go("Arith.Divide", args, quotient, nil)
replyCall := <-divCall.Done	// will be equal to divCall
// check errors, print, etc.

A server implementation will often provide a simple, type-safe wrapper for the client.

The net/rpc package is frozen and is not accepting new features.

type Request

Request is a header written before every RPC call. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type Request struct {
    ServiceMethod string // format: "Service.Method"
    Seq           uint64 // sequence number chosen by client
    // contains filtered or unexported fields
}

type Response

Response is a header written before every RPC return. It is used internally but documented here as an aid to debugging, such as when analyzing network traffic.

type Response struct {
    ServiceMethod string // echoes that of the Request
    Seq           uint64 // echoes that of the request
    Error         string // error, if any.
    // contains filtered or unexported fields
}

type ServerCodec

A ServerCodec implements reading of RPC requests and writing of RPC responses for the server side of an RPC session. The server calls ReadRequestHeader and ReadRequestBody in pairs to read requests from the connection, and it calls WriteResponse to write a response back. The server calls Close when finished with the connection. ReadRequestBody may be called with a nil argument to force the body of the request to be read and discarded. See NewClient’s comment for information about concurrent access.

type ServerCodec interface {
    ReadRequestHeader(*Request) error
    ReadRequestBody(interface{}) error
    WriteResponse(*Response, interface{}) error

    // Close can be called multiple times and must be idempotent.
    Close() error
}

type ServerError

ServerError represents an error that has been returned from the remote side of the RPC connection.

type ServerError string

type Client

Client represents an RPC Client.

  • There may be multiple outstanding Calls associated with a single Client
  • And a Client may be used by multiple goroutines simultaneously.
// contains filtered or unexported fields
type Client struct {
	codec ClientCodec
	reqMutex sync.Mutex // protects following
	request  Request
	mutex    sync.Mutex // protects following
	seq      uint64
	pending  map[uint64]*Call
	closing  bool // user has called Close
	shutdown bool // server has told us to stop
}

func (*Client) Call

func (client *Client) Call(serviceMethod string, 
						   args interface{}, 
						   reply interface{}) error

Call invokes the named function, waits for it to complete, and returns its error status.

The Call function executes a remote procedure synchronously, which means, the goroutine (function execution) will be blocked until the response is returned. The serviceMethod argument should specify the exact procedure name in <Type>.<Method> format.

The args argument specifies the payload of the procedure call and reply is pointer to hold the result of the procedure call. These two values should exactly match the procedure method definition. The error return value will be non-nil in case the procedure returns an error.

在MIT 6.824的raft实验中:

//
// example code to send a RequestVote RPC to a server.
// server is the index of the target server in rf.peers[].
// expects RPC arguments in args.
// fills in *reply with RPC reply, so caller should pass &reply.
// the types of the args and reply passed to Call() must be
// the same as the types of the arguments declared in the
// handler function (including whether they are pointers).
//
// The labrpc package simulates a lossy network, in which servers
// may be unreachable, and in which requests and replies may be lost.
// Call() sends a request and waits for a reply. If a reply arrives
// within a timeout interval, Call() returns true; otherwise
// Call() returns false. Thus Call() may not return for a while.
// A false return can be caused by a dead server, a live server that
// can't be reached, a lost request, or a lost reply.
//
// Call() is guaranteed to return (perhaps after a delay) *except* if the
// handler function on the server side does not return.  Thus there
// is no need to implement your own timeouts around Call().
//
// look at the comments in ../labrpc/labrpc.go for more details.
//
// if you're having trouble getting RPC to work, check that you've
// capitalized all field names in structs passed over RPC, and
// that the caller passes the address of the reply struct with &, not
// the struct itself.
//
func (rf *Raft) sendRequestVote(server int,
								args *RequestVoteArgs,
								reply *RequestVoteReply) bool {
	// Synchronous call
	ok := rf.peers[server].Call("Raft.RequestVote", args, reply)
	return ok
}
func (rf *Raft) sendAppendEntries(server int, 
								  args *AppendEntriesArgs, 
								  reply *AppendEntriesReply) bool {
	// Synchronous call
	ok := rf.peers[server].Call("Raft.AppendEntries", args, reply)
	return ok
}

func (*Client) Go

func (client *Client) Go(serviceMethod string, 
                         args interface{}, 
                         reply interface{}, 
                         done chan *Call) *Call

Go invokes the function asynchronously. It returns the Call structure representing the invocation. The done channel will signal when the call is complete by returning the same Call object. If done is nil, Go will allocate a new channel. If non-nil, done must be buffered or Go will deliberately crash.

The *Client.Go method sends an RPC request in a separate goroutine and returns a *Call object. This call does not block the current goroutine until the response is received. You will be notified of the response or an error using the *Call object which provides Done and Error channels for the same.

type Server

Server represents an RPC Server.

// Server represents an RPC Server.
type Server struct { //server对象
	serviceMap sync.Map   // map[string]*service 保存服务提供者信息的map
	reqLock    sync.Mutex // protects freeReq 用于做freeReq的同步
	freeReq    *Request //rpc 请求
	respLock   sync.Mutex // protects freeResp 用于做freeResp的同步
	freeResp   *Response //rpc响应
}
// 保存了服务提供者的各个信息,包括名称、类型、方法等等
type service struct { 
	name   string                 // name of service
	rcvr   reflect.Value          // receiver of methods for the service
	typ    reflect.Type           // type of the receiver
	method map[string]*methodType // registered methods
}
// 保存了反射获取到的方法的相关信息,
// 此外还有一个计数器,用来统计调用次数,
// 还有一个继承的Mutext接口,用来做计数器的同步
type methodType struct {
	sync.Mutex // protects counters
	method     reflect.Method
	ArgType    reflect.Type
	ReplyType  reflect.Type
	numCalls   uint
}

func (*Server) Register

func (server *Server) Register(rcvr interface{}) error

Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:

  • exported method of exported type
  • two arguments, both of exported type
  • the second argument is a pointer
  • one return value, of type error

It returns an error if the receiver is not an exported type or has no suitable methods. It also logs the error using package log. The client accesses each method using a string of the form “Type.Method”, where Type is the receiver’s concrete type.

func (*Server) RegisterName

func (server *Server) RegisterName(name string, rcvr interface{}) error

RegisterName is like Register but uses the provided name for the type instead of the receiver’s concrete type.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值