本文首先介绍一下RPC,然后展示一下RPC开发服务端和客户端的主要代码示例。
RPC 介绍
RPC 定义
A remote procedure call (RPC) is when a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network), which is coded as if it were a normal (local) procedure call, without the programmer explicitly coding the details for the remote interaction.This is a form of client–server interaction (caller is client, executor is server), typically implemented via a request–response message-passing system
以上是维基百科对RPC的定义。
远程过程调用(Remote Procedure Call,缩写 RPC)是一个请求-响应协议,允许允许于一台计算机的程序调用另一台计算机的子程序,而无需开发人员额外地为这个交互作用编程。RPC 是一个客户端-服务端(C/S)的例子,总是由客户端对服务器发出一个执行若干过程请求,并携带服务端所需的参数;服务端使用客户端提供的参数处理请求,将执行结果返回给客户端。
RPC模型
服务的调用流程:
- client调用client stub,本地过程调用,参数以正常方式压入堆栈
- client stub 将参数打包成一个消息,然后发送这个消息。这个打包过程也称为marshalling
- client所在的操作系统将消息发送给server
- server所在的操作系统将收到的包传给server stub
- server stub解包得到参数。解包也称作unmarshalliing
- 最后server stub执行服务程序。反方向同样步骤将结果返回给客户端
示例
Go 官方提供一个标准 RPC库: net/rpc
。
Golang 的 rpc 支持三个级别的 RPC: TCP、HTTP、JSONRPC。但 Go 的 RPC 包只支持 Go 开发的服务器与客户端之间的交互,因为内部采用 Gob 来编码。
Go RPC 服务端通过注册对象,使用对象的类型名暴露服务。服务端可以注册多个不同类型的对象