json-rpc

json-rpc 是 rpc 通信過(guò)程中定義的一套 json 格式標(biāo)準(zhǔn),最早是 json-rpc1.0,最新是 json-rpc2.0裙顽。

使用 json 格式來(lái)通信,通信的雙方 client宣谈,server 必須約定好統(tǒng)一的字段,以便彼此能互相解析键科,這就是 json-rpc 標(biāo)準(zhǔn)的來(lái)由闻丑。

根據(jù) 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官方庫(kù)實(shí)現(xiàn)了JSON-RPC 1.0勋颖。JSON-RPC是一個(gè)通過(guò)JSON格式進(jìn)行消息傳輸?shù)腞PC規(guī)范嗦嗡,因此可以進(jìn)行跨語(yǔ)言的調(diào)用。

源文件: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()饭玲,可見(jiàn) WriteRequest() 函數(shù)最終把請(qǐng)求 encode 成 json 格式發(fā)送了侥祭。

調(diào)用流程分析:

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)
}

這里是調(diào)用的 c.Call("Arith.Mult", args, &reply") 來(lái)實(shí)現(xiàn)發(fā)送 json-rpc request 到服務(wù)器的。
Call() 函數(shù)內(nèi)部的調(diào)用過(guò)程如下:
源文件: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 庫(kù)可以將 JSON-RPC 的請(qǐng)求轉(zhuǎn)換成自己內(nèi)部的格式,比如 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 語(yǔ)言官方庫(kù)目前不支持 JSON-RPC 2.0 矮冬,但是有第三方開(kāi)發(fā)者提供了實(shí)現(xiàn)谈宛,比如:
https://github.com/powerman/rpc-codec
https://github.com/dwlnetnl/generpc

一些其它的 codec 如 bsonrpcmessagepack胎署、protobuf 等吆录。
如果你使用其它特定的序列化框架,你可以參照這些實(shí)現(xiàn)來(lái)寫(xiě)一個(gè)你自己的 rpc codec琼牧。
關(guān)于 Go 序列化庫(kù)的性能的比較可以參考 gosercomp恢筝。

注意:
Go 語(yǔ)言提供的 jsonrpc 包不支持 json-rpc over HTTP,因此我們不能通過(guò) curl 命令來(lái)給 Server 發(fā)送請(qǐng)求來(lái)測(cè)試巨坊。如果我們真的需要用 http 請(qǐng)求來(lái)測(cè)試的話(huà)撬槽,那么我們就應(yīng)該提供一個(gè) HTTP Hanlder 來(lái)處理 HTTP request/response,然后把他適配到 ServerCodec 函數(shù)中去趾撵,比如:

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()
}

現(xiàn)在侄柔,我們就可以用 curl 命令來(lái)測(cè)試了,比如:

$ curl -X POST -H "Content-Type: application/json" -d '{"id": 1, "method": "Test.Greet", "params": [{"name":"world"}]}' http://localhost:8080/test

網(wǎng)上也有 json-rpc over http 的第三方開(kāi)源庫(kù)鼓寺,比如 gorilla/rpc

使用 gorrlla/rpc 的實(shí)例:
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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末勋拟,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子妈候,更是在濱河造成了極大的恐慌敢靡,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件苦银,死亡現(xiàn)場(chǎng)離奇詭異啸胧,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)幔虏,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)纺念,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人想括,你說(shuō)我怎么就攤上這事陷谱。” “怎么了瑟蜈?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,324評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵烟逊,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我铺根,道長(zhǎng)宪躯,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,714評(píng)論 1 297
  • 正文 為了忘掉前任位迂,我火速辦了婚禮访雪,結(jié)果婚禮上详瑞,老公的妹妹穿的比我還像新娘。我一直安慰自己臣缀,他們只是感情好坝橡,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,724評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著肝陪,像睡著了一般驳庭。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上氯窍,一...
    開(kāi)封第一講書(shū)人閱讀 52,328評(píng)論 1 310
  • 那天饲常,我揣著相機(jī)與錄音,去河邊找鬼狼讨。 笑死贝淤,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的政供。 我是一名探鬼主播播聪,決...
    沈念sama閱讀 40,897評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼布隔!你這毒婦竟也來(lái)了离陶?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,804評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤衅檀,失蹤者是張志新(化名)和其女友劉穎招刨,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體哀军,經(jīng)...
    沈念sama閱讀 46,345評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡沉眶,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,431評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了杉适。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片谎倔。...
    茶點(diǎn)故事閱讀 40,561評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖猿推,靈堂內(nèi)的尸體忽然破棺而出片习,到底是詐尸還是另有隱情,我是刑警寧澤蹬叭,帶...
    沈念sama閱讀 36,238評(píng)論 5 350
  • 正文 年R本政府宣布毯侦,位于F島的核電站,受9級(jí)特大地震影響具垫,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜试幽,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,928評(píng)論 3 334
  • 文/蒙蒙 一筝蚕、第九天 我趴在偏房一處隱蔽的房頂上張望卦碾。 院中可真熱鬧,春花似錦起宽、人聲如沸洲胖。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,417評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)绿映。三九已至,卻和暖如春腐晾,著一層夾襖步出監(jiān)牢的瞬間叉弦,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,528評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工藻糖, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留淹冰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,983評(píng)論 3 376
  • 正文 我出身青樓巨柒,卻偏偏與公主長(zhǎng)得像樱拴,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子洋满,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,573評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容