Golang RPC 之 gRPC

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

gRPC 簡介:

gRPC 是一款高效能、開源的 RPC 架構,產自 Google,基於 ProtoBuf 序列化協議進行開發,支援多種語言(Golang、Python、Java等)。因為 gRPC 對 HTTP/2 協議的支援使其在 Android、IOS 等用戶端後端服務的開發領域具有良好的前景。gRPC 提供了一種簡單的方法來定義服務,同時用戶端可以充分利用 HTTP2 stream 的特性,從而有助於節省頻寬、降低 TCP 的串連次數、節省CPU的使用等。

安裝:

  1. gRPC 的安裝

    $ go get -u google.golang.org/grpc

  2. 因為 gRPC 是基於 protobuf 實現的介面序列化,所以也要安裝 protobuf: 安裝及簡介教程。

實踐:

下面我們使用 gRPC 定義一個介面,該介面實現對傳入的資料進行大寫的格式化處理。

  1. 建立項目 golang Demo 工程:


    Paste_Image.png
    1. client目錄下的 main.go 實現了用戶端用於發送資料並列印接收到 server 端處理後的資料
    2. server 目錄下的 main.go 實現了服務端用於接收用戶端發送的資料,並對資料進行大寫處理後返回給用戶端
    3. example 包使用者編寫 proto 檔案並產生 data 介面
  2. 定義 gRPC 介面:

    syntax = "proto3";package example;service FormatData { rpc DoFormat(Data) returns (Data){}}message Data { string text = 1;}
  3. 實現 server 端

    package mainimport ( "Demo/example" "net" "google.golang.org/grpc" "google.golang.org/grpc/reflection" "golang.org/x/net/context" "strings" "log")// 定義監聽地址const ( HOST string = "localhost" PORT string = "8080")// 定義介面type FormatData struct{}func (fd *FormatData) DoFormat(ctx context.Context, in *example.Data) (out *example.Data, err error) { str := in.Text out = &example.Data{Text: strings.ToUpper(str)} return out, nil}// 直接在 main 方法中註冊介面func main() { listener, err := net.Listen("tcp", HOST+":"+PORT) if err != nil {     log.Fatalln("faile listen at: " + HOST + ":" + PORT) } else {     log.Println("Demo server is listening at: " + HOST + ":" + PORT) } rpcServer := grpc.NewServer() example.RegisterFormatDataServer(rpcServer, &FormatData{}) reflection.Register(rpcServer) if err = rpcServer.Serve(listener); err != nil {     log.Fatalln("faile serve at: " + HOST + ":" + PORT) }}
  4. 實現 client 端:
    package mainimport ( "google.golang.org/grpc" "log" "Demo/example" "golang.org/x/net/context")// 定義請求地址const ( ADDRESS string = "localhost:8080")// main 方法實現對 gRPC 介面的請求func main() { conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure()) if err != nil {     log.Fatalln("Can't connect: " + ADDRESS) } defer conn.Close() client := example.NewFormatDataClient(conn) resp,err := client.DoFormat(context.Background(), &example.Data{Text:"hello,world!"}) if err != nil {     log.Fatalln("Do Format error:" + err.Error()) } log.Println(resp.Text)}
  5. 執行驗證結果:
    1. 先啟動 server,之後再執行 client
    2. client 側控制台如果列印的結果為: HELLO,WORLD! ,證明 gRPC 介面定義成功

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.