json-rpc 是 rpc 通信过程中定义的一套 json 格式标准,最早是 json-rpc1.0,最新是 json-rpc2.0。
使用 json 格式来通信,通信的双方 client,server 必须约定好统一的字段,以便彼此能互相解析,这就是 json-rpc 标准的来由。
根据 json-rpc 1.0 约定,Request 和 Response 的格式必须符合如下要求:
(1)Request
- method A String containing the name of the method to be invoked.
- params An Array of objects to pass as arguments to the method.
- id The request id. This can be of any type. It is used to match the response with the request that it is replying to.
(2)Response
- result The Object that was returned by the invoked method. This must be null in - - case there was an error invoking the method.
- error An Error object if there was an error invoking the method. It must be null if there was no error.
- id This must be the same id as the request it is responding to.
例子:
request:data sent to service
{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}
response:data coming from service
{ "result": "Hello JSON-RPC", "error": null, "id": 1}
json-rpc2.0
(1)Request
- jsonrpc - A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
- method - A String containing the name of the method to be invoked.
- params - An Array of objects to pass as arguments to the method.
- id - The request id. This can be of any type. It is used to match the response with the request that it is replying to.
(2)Response
- jsonrpc - A String specifying the version of the JSON-RPC protocol. MUST be exactly "2.0".
- result - The Object that was returned by the invoked method. This must be null in case there was an error invoking the method.
- error - An Error object if there was an error invoking the method. It must be null if there was no error.
- id - This must be the same id as the request it is responding to.
Notification
A Notification is a Request object without an "id" member. A Request object that is a Notification signifies the Client's lack of interest in the corresponding Response object, and as such no Response object needs to be returned to the client.
The Server MUST NOT reply to a Notification, including those that are within a batch request.
例子:
request:data sent to service
{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}
response:data coming from service
{"jsonrpc": "2.0", "result": 19, "id": 1}
a notification request
{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}
a notification response
{"jsonrpc": "2.0", "method": "foobar"}
json-rpc1.0 VS json-rpc2.0
- "jsonrpc" field added added a version-field to the Request (and also to the Response) to resolve compatibility issues with JSON-RPC 1.0.
-
client-server instead of peer-to-peer:
JSON-RPC 2.0 uses a client-server-architecture.
V1.0 used a peer-to-peer-architecture where every peer was both server and client. -
Transport independence:
JSON-RPC 2.0 doesn't define any transport-specific issues, since transport and RPC are independent.
V1.0 defined that exceptions must be raised if the connection is closed, and that invalid requests/responses must close the connection (and raise exceptions). - Named parameters added (see Example below)
-
Reduced fields:
- Request: params may be omitted
- Notification: doesn't contain an id anymore
- Response: contains only
result
ORerror
(but not both)
- Optional parameters: defined that unspecified optional parameters SHOULD use a default-value.
- Error-definitions added
Go官方库实现了JSON-RPC 1.0。JSON-RPC是一个通过JSON格式进行消息传输的RPC规范,因此可以进行跨语言的调用。
源文件:rpc/jsonrpc/client.go
type clientRequest struct {
Method string `json:"method"`
Params [1]interface{} `json:"params"`
Id uint64 `json:"id"`
}
func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error {
c.mutex.Lock()
c.pending[r.Seq] = r.ServiceMethod
c.mutex.Unlock()
c.req.Method = r.ServiceMethod
c.req.Params[0] = param
c.req.Id = r.Seq
return c.enc.Encode(&c.req)
}
上面的 enc 就是 json.Encoder()
,可见 WriteRequest()
函数最终把请求 encode 成 json 格式发送了。
调用流程分析:
func CallRpcService(c *rpc.Client) {
args := &server.Args{7, 8}
var reply int
err := c.Call("Arith.Mult", args, &reply)
if err != nil {
log.Fatal("Arith error: ", err)
}
fmt.Printf("Arith: %d*%d= %d\n", args.A, args.B, reply)
}
这里是调用的 c.Call("Arith.Mult", args, &reply")
来实现发送 json-rpc request 到服务器的。
Call() 函数内部的调用过程如下:
源文件:rpc/client.go
// (1)
func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error {
call := <-client.Go(serviceMethod, args, reply, make(chan *Call, 1)).Done
return call.Error
}
// (2)
func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call {
call := new(Call)
call.ServiceMethod = serviceMethod
call.Args = args
call.Reply = reply
...
client.send(call)
return call
}
// (3)
func (client *Client) send(call *Call) {
...
// Encode and send the request.
client.request.Seq = seq
client.request.ServiceMethod = call.ServiceMethod
err := client.codec.WriteRequest(&client.request, call.Args)
...
}
源文件:rpc/jsonrpc/client.go
// (4)
func (c *clientCodec) WriteRequest(r *rpc.Request, param interface{}) error {
c.mutex.Lock()
c.pending[r.Seq] = r.ServiceMethod
c.mutex.Unlock()
c.req.Method = r.ServiceMethod
c.req.Params[0] = param
c.req.Id = r.Seq
return c.enc.Encode(&c.req)
}
Go 的 net/rpc/jsonrpc
库可以将 JSON-RPC 的请求转换成自己内部的格式,比如 request header 的处理:
func (c *serverCodec) ReadRequestHeader(r *rpc.Request) error {
c.req.reset()
if err := c.dec.Decode(&c.req); err != nil {
return err
}
r.ServiceMethod = c.req.Method
c.mutex.Lock()
c.seq++
c.pending[c.seq] = c.req.Id
c.req.Id = nil
r.Seq = c.seq
c.mutex.Unlock()
return nil
}
Go 语言官方库目前不支持 JSON-RPC 2.0 ,但是有第三方开发者提供了实现,比如:
https://github.com/powerman/rpc-codec
https://github.com/dwlnetnl/generpc
一些其它的 codec 如 bsonrpc、messagepack、protobuf 等。
如果你使用其它特定的序列化框架,你可以参照这些实现来写一个你自己的 rpc codec。
关于 Go 序列化库的性能的比较可以参考 gosercomp。
注意:
Go 语言提供的 jsonrpc 包不支持 json-rpc over HTTP,因此我们不能通过 curl 命令来给 Server 发送请求来测试。如果我们真的需要用 http 请求来测试的话,那么我们就应该提供一个 HTTP Hanlder 来处理 HTTP request/response,然后把他适配到 ServerCodec 函数中去,比如:
package main
import (
"io"
"log"
"net"
"net/http"
"net/rpc"
"net/rpc/jsonrpc"
"os"
)
const addr = "localhost:8080"
type HttpConn struct {
in io.Reader
out io.Writer
}
func (c *HttpConn) Read(p []byte) (n int, err error) { return c.in.Read(p) }
func (c *HttpConn) Write(d []byte) (n int, err error) { return c.out.Write(d) }
func (c *HttpConn) Close() error { return nil }
// RPC Api structure
type Test struct{}
// Greet method arguments
type GreetArgs struct {
Name string
}
// Grret message accept object with single param Name
func (test *Test) Greet(args *GreetArgs, result *string) error {
*result = "Hello " + args.Name
return nil
}
// Start server with Test instance as a service
func startServer() {
test := new(Test)
server := rpc.NewServer()
server.Register(test)
listener, err := net.Listen("tcp", addr)
if err != nil {
log.Fatal("listen error:", err)
}
defer listener.Close()
http.Serve(listener, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/test" {
serverCodec := jsonrpc.NewServerCodec(&HttpConn{in: r.Body, out: w})
w.Header().Set("Content-type", "application/json")
w.WriteHeader(200)
err := server.ServeRequest(serverCodec)
if err != nil {
log.Printf("Error while serving JSON request: %v", err)
http.Error(w, "Error while serving JSON request, details have been logged.", 500)
return
}
}
}))
}
func main() {
startServer()
}
现在,我们就可以用 curl 命令来测试了,比如:
$ curl -X POST -H "Content-Type: application/json" -d '{"id": 1, "method": "Test.Greet", "params": [{"name":"world"}]}' http://localhost:8080/test
网上也有 json-rpc over http 的第三方开源库,比如 gorilla/rpc
使用 gorrlla/rpc 的实例:
https://haisum.github.io/2015/10/13/rpc-jsonrpc-gorilla-example-in-golang/
参考:
http://www.simple-is-better.org/rpc/#differences-between-1-0-and-2-0