json-rpc

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 OR error (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 如 bsonrpcmessagepackprotobuf 等。
如果你使用其它特定的序列化框架,你可以参照这些实现来写一个你自己的 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,921评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,635评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,393评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,836评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,833评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,685评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,043评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,694评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,671评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,670评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,779评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,424评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,027评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,984评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,214评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,108评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,517评论 2 343

推荐阅读更多精彩内容