micro學(xué)習(xí)筆記:client

接口

type Client interface {
    Init(...Option) error
    Options() Options
    NewPublication(topic string, msg interface{}) Publication
    NewRequest(service, method string, req interface{}, reqOpts ...RequestOption) Request
    NewProtoRequest(service, method string, req interface{}, reqOpts ...RequestOption) Request
    NewJsonRequest(service, method string, req interface{}, reqOpts ...RequestOption) Request
    Call(ctx context.Context, req Request, rsp interface{}, opts ...CallOption) error
    CallRemote(ctx context.Context, addr string, req Request, rsp interface{}, opts ...CallOption) error
    Stream(ctx context.Context, req Request, opts ...CallOption) (Streamer, error)
    StreamRemote(ctx context.Context, addr string, req Request, opts ...CallOption) (Streamer, error)
    Publish(ctx context.Context, p Publication, opts ...PublishOption) error
    String() string
}

用例

// Create new request to service go.micro.srv.example, method Example.Call
    req := client.NewRequest("go.micro.srv.example", "Example.Call", &example.Request{
        Name: "John",
    })

    // create context with metadata
    ctx := metadata.NewContext(context.Background(), map[string]string{
        "X-User-Id": "john",
        "X-From-Id": "script",
    })

    rsp := &example.Response{}

    // Call service
    if err := client.Call(ctx, req, rsp); err != nil {
        fmt.Println("call err: ", err, rsp)
        return
    }

    fmt.Println("Call:", i, "rsp:", rsp.Msg)

操作流程

大致流程分三步库倘,實(shí)例化巴元,構(gòu)建Request舵盈,發(fā)起請(qǐng)求 Call

  • 1陋率、client := NewClient() // 實(shí)例化,可以直接用client秽晚,默認(rèn)客戶端(上例中使用)
    -- 1.1瓦糟、client.Init(...opts) // 初始化client , 可以在NewClient時(shí)配置,也可以在init配置赴蝇,可配置項(xiàng)見默認(rèn)配置
  • 2菩浙、構(gòu)建Request,其實(shí)就是構(gòu)建一個(gè)用戶發(fā)送請(qǐng)求的結(jié)構(gòu)
func (r *rpcClient) NewRequest(service, method string, request interface{}, reqOpts ...RequestOption) Request {
    return newRpcRequest(service, method, request, r.opts.ContentType, reqOpts...)
}

func (r *rpcClient) NewProtoRequest(service, method string, request interface{}, reqOpts ...RequestOption) Request {
    return newRpcRequest(service, method, request, "application/octet-stream", reqOpts...)
}

func (r *rpcClient) NewJsonRequest(service, method string, request interface{}, reqOpts ...RequestOption) Request {
    return newRpcRequest(service, method, request, "application/json", reqOpts...)
}

func newRpcRequest(service, method string, request interface{}, contentType string, reqOpts ...RequestOption) Request {
    var opts RequestOptions

    for _, o := range reqOpts {
        o(&opts)
    }

    return &rpcRequest{
        service:     service,
        method:      method,
        request:     request,
        contentType: contentType,
        opts:        opts,
    }
}
  • 3、發(fā)起請(qǐng)求 Call劲蜻,重點(diǎn)陆淀!看看客戶端怎樣發(fā)起請(qǐng)求的
    -- 3.1 opts.Selector.Select(request.Service(), callOpts.SelectOptions...) 選擇服務(wù)端服務(wù)器地址
    ---- 3.1.1 services, err := r.so.Registry.GetService(service) 從服務(wù)發(fā)現(xiàn)服務(wù)中取對(duì)應(yīng)所有服務(wù)器列表
    ---- 3.1.2 sopts.Strategy(services) 從列表中按選擇策略選出一個(gè)服務(wù)器地址,默認(rèn)策略:Random
// get next nodes from the selector
    next, err := r.opts.Selector.Select(request.Service(), callOpts.SelectOptions...)
    if err != nil && err == selector.ErrNotFound {
        return errors.NotFound("go.micro.client", err.Error())
    } else if err != nil {
        return errors.InternalServerError("go.micro.client", err.Error())
    }

-- 3.2 構(gòu)建context

    // check if we already have a deadline
    d, ok := ctx.Deadline()
    if !ok {
        // no deadline so we create a new one
        ctx, _ = context.WithTimeout(ctx, callOpts.RequestTimeout)
    } else {
        // got a deadline so no need to setup context
        // but we need to set the timeout we pass along
        opt := WithRequestTimeout(d.Sub(time.Now()))
        opt(&callOpts)
    }

    // should we noop right here?
    select {
    case <-ctx.Done():
        return errors.New("go.micro.client", fmt.Sprintf("%v", ctx.Err()), 408)
    default:
    }

-- 3.3 請(qǐng)求外圍調(diào)用斋竞,類似于請(qǐng)求中間件機(jī)制

// make copy of call method
    rcall := r.call

    // wrap the call in reverse
    for i := len(callOpts.CallWrappers); i > 0; i-- {
        rcall = callOpts.CallWrappers[i-1](rcall)
    }

-- 3.4 完整的調(diào)用方法

// return errors.New("go.micro.client", "request timeout", 408)
    call := func(i int) error {
        // call backoff first. Someone may want an initial start delay
    // delay 機(jī)制,出錯(cuò)的時(shí)候可以指定下一次執(zhí)行時(shí)間
        t, err := callOpts.Backoff(ctx, request, i)
        if err != nil {
            return errors.InternalServerError("go.micro.client", err.Error())
        }

        // only sleep if greater than 0
        if t.Seconds() > 0 {
            time.Sleep(t)
        }

        // select next node  取服務(wù)端節(jié)點(diǎn)
        node, err := next()
        if err != nil && err == selector.ErrNotFound {
            return errors.NotFound("go.micro.client", err.Error())
        } else if err != nil {
            return errors.InternalServerError("go.micro.client", err.Error())
        }

        // set the address
        address := node.Address
        if node.Port > 0 {
            address = fmt.Sprintf("%s:%d", address, node.Port)
        }

        // make the call 發(fā)送請(qǐng)求
        err = rcall(ctx, address, request, response, callOpts)
        r.opts.Selector.Mark(request.Service(), node, err)  // 標(biāo)記,用于記錄錯(cuò)誤秃殉,優(yōu)化選擇器
        return err
    }

-- 3.4 重試機(jī)制

ch := make(chan error, callOpts.Retries)
    var gerr error

    for i := 0; i < callOpts.Retries; i++ {
        go func() {
            ch <- call(i)
        }()

        select {
        case <-ctx.Done():
            return errors.New("go.micro.client", fmt.Sprintf("call timeout: %v", ctx.Err()), 408)
        case err := <-ch:
            // if the call succeeded lets bail early
            if err == nil {
                return nil
            }

            retry, rerr := callOpts.Retry(ctx, request, i, err)
            if rerr != nil {
                return rerr
            }

            if !retry {
                return err
            }

            gerr = err
        }
    }
  • 4 真正的call
    -- 4.1 構(gòu)建 請(qǐng)求header
msg := &transport.Message{
        Header: make(map[string]string),
    }

    md, ok := metadata.FromContext(ctx)
    if ok {
        for k, v := range md {
            msg.Header[k] = v
        }
    }

    // set timeout in nanoseconds
    msg.Header["Timeout"] = fmt.Sprintf("%d", opts.RequestTimeout)
    // set the content type for the request
    msg.Header["Content-Type"] = req.ContentType()
    // set the accept header
    msg.Header["Accept"] = req.ContentType()

-- 4.2 newCodec , 根據(jù) contentType 初始化encode方式坝初,json or protobuf

defaultCodecs = map[string]codec.NewCodec{
        "application/json":         jsonrpc.NewCodec,
        "application/json-rpc":     jsonrpc.NewCodec,
        "application/protobuf":     protorpc.NewCodec,
        "application/proto-rpc":    protorpc.NewCodec,
        "application/octet-stream": protorpc.NewCodec,
    }

cf, err := r.newCodec(req.ContentType())
    if err != nil {
        return errors.InternalServerError("go.micro.client", err.Error())
    }

-- 4.3 從連接池中取連接實(shí)例

var grr error
    c, err := r.pool.getConn(address, r.opts.Transport, transport.WithTimeout(opts.DialTimeout))
    if err != nil {
        return errors.InternalServerError("go.micro.client", "connection error: %v", err)
    }
    defer func() {
        // defer execution of release
        r.pool.release(address, c, grr)
    }()

-- 4.4 發(fā)送請(qǐng)求

    stream := &rpcStream{
        context: ctx,
        request: req,
        closed:  make(chan bool),
        codec:   newRpcPlusCodec(msg, c, cf),
    }
    defer stream.Close()

    ch := make(chan error, 1)

    go func() {
        defer func() {
            if r := recover(); r != nil {
                ch <- errors.InternalServerError("go.micro.client", "panic recovered: %v", r)
            }
        }()

        // send request
        if err := stream.Send(req.Request()); err != nil {
            ch <- err
            return
        }

        // recv request
        if err := stream.Recv(resp); err != nil {
            ch <- err
            return
        }

        // success
        ch <- nil
    }()

    select {
    case err := <-ch:
        grr = err
        return err
    case <-ctx.Done():
        grr = ctx.Err()
        return errors.New("go.micro.client", fmt.Sprintf("request timeout: %v", ctx.Err()), 408)
    }

stream.Send 調(diào)用codec.WriteRequest
stream.Recv 調(diào)用codec.ReadResponseHeader,codec.ReadResponseBody

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末钾军,一起剝皮案震驚了整個(gè)濱河市鳄袍,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吏恭,老刑警劉巖拗小,帶你破解...
    沈念sama閱讀 217,657評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異樱哼,居然都是意外死亡哀九,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門搅幅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)阅束,“玉大人,你說(shuō)我怎么就攤上這事茄唐∠⒙悖” “怎么了?”我有些...
    開封第一講書人閱讀 164,057評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵沪编,是天一觀的道長(zhǎng)呼盆。 經(jīng)常有香客問(wèn)我,道長(zhǎng)蚁廓,這世上最難降的妖魔是什么访圃? 我笑而不...
    開封第一講書人閱讀 58,509評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮相嵌,結(jié)果婚禮上挽荠,老公的妹妹穿的比我還像新娘。我一直安慰自己平绩,他們只是感情好圈匆,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,562評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著捏雌,像睡著了一般跃赚。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評(píng)論 1 302
  • 那天纬傲,我揣著相機(jī)與錄音满败,去河邊找鬼。 笑死叹括,一個(gè)胖子當(dāng)著我的面吹牛算墨,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播汁雷,決...
    沈念sama閱讀 40,251評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼净嘀,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了侠讯?” 一聲冷哼從身側(cè)響起挖藏,我...
    開封第一講書人閱讀 39,129評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎厢漩,沒(méi)想到半個(gè)月后膜眠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,561評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡溜嗜,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,779評(píng)論 3 335
  • 正文 我和宋清朗相戀三年宵膨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片炸宵。...
    茶點(diǎn)故事閱讀 39,902評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡柄驻,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出焙压,到底是詐尸還是另有隱情鸿脓,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評(píng)論 5 345
  • 正文 年R本政府宣布涯曲,位于F島的核電站野哭,受9級(jí)特大地震影響姻乓,放射性物質(zhì)發(fā)生泄漏鞠抑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,220評(píng)論 3 328
  • 文/蒙蒙 一匾竿、第九天 我趴在偏房一處隱蔽的房頂上張望绰沥。 院中可真熱鬧篱蝇,春花似錦、人聲如沸徽曲。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)秃臣。三九已至涧衙,卻和暖如春哪工,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背弧哎。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工雁比, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人撤嫩。 一個(gè)月前我還...
    沈念sama閱讀 48,025評(píng)論 2 370
  • 正文 我出身青樓偎捎,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親序攘。 傳聞我的和親對(duì)象是個(gè)殘疾皇子茴她,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,843評(píng)論 2 354

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