grpc 簡單使用

參考:golang grpc 快速開始
以 windows 平臺為例:

go get google.golang.org/protobuf/cmd/protoc-gen-go 
 go get  google.golang.org/grpc/cmd/protoc-gen-go-grpc
因為我當前 的 gopath 就是f:/go 所以 直接把get 包安裝到了 bin 目錄

gopath/bin 要加入到環境變量

然后就可以試一下 grpc 了

  • 直接用 官方的例子
git clone -b v1.35.0 https://github.com/grpc/grpc-go
cd grpc-go/examples/helloworld
go run greeter_server/main.go
go run greeter_client/main.go
# greeter_client控制臺輸出:
> Greeting: Hello world

  • 修改 rpc 服務的函數
    在 helloworld/helloworld.proto 添加SayHelloAgain()具有相同請
    求和響應類型的新方法,改成如下文件
// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

  • 重新編譯更新的 .proto 文件
protoc --go_out=. --go_opt=paths=source_relative \
    --go-grpc_out=. --go-grpc_opt=paths=source_relative \
    helloworld/helloworld.proto
image.png

重新生成 了 helloworld/helloworld.pb.go和helloworld/helloworld_grpc.pb.go文件
我們 上面新添加了 一個 rpc 函數 : SayHelloAgain

  • 修改 greeter_server/main.go
    添加下面的代碼
func (s *server) SayHelloAgain(ctx context.Context, in 
*pb.HelloRequest) (*pb.HelloReply, error) {
        return &pb.HelloReply{Message: "Hello again " + in.GetName()}, nil
}
  • 修改 greeter_client/main.go

main 函數末尾添加 :

r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: name})
if err != nil {
        log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", r.GetMessage())
  • 分別運行 greeter_server/main.go 和 greeter_client/main.go

更全面的官方教程在此, 包含普通,客戶端流,服務端流,雙向流

簡單介紹一下四種模式下的基本用法(既然看了,還是要記錄一下的)

服務端:

  • 普通的調用
func (s *routeGuideServer) GetFeature(ctx context.Context, point 
*pb.Point) (*pb.Feature, error) {
    for _, feature := range s.savedFeatures {
        if proto.Equal(feature.Location, point) {
            return feature, nil
        }
    }
    // No feature was found, return an unnamed feature
    return &pb.Feature{Location: point}, nil
}
  • 服務端流 ( stream.Send 不斷發響應)
// 服務端流 
func (s *routeGuideServer) ListFeatures(rect *pb.Rectangle, 
stream pb.RouteGuide_ListFeaturesServer) error {
    for _, feature := range s.savedFeatures {
        if inRange(feature.Location, rect) {
            if err := stream.Send(feature); err != nil {
                return err
            }
        }
    }
    return nil
}
  • 客戶端流 ( stream.Recv() 不斷取值, 遇到 io.EOF 的錯誤,就調用 stream.SendAndClose 返回值,并通知客戶端函數執行完畢)
func (s *routeGuideServer) RecordRoute(stream pb.RouteGuide_RecordRouteServer) error {
    var pointCount, featureCount, distance int32
    var lastPoint *pb.Point
    startTime := time.Now()
    for {
        point, err := stream.Recv()
        if err == io.EOF {
            endTime := time.Now()
            return stream.SendAndClose(&pb.RouteSummary{
                PointCount:   pointCount,
                FeatureCount: featureCount,
                Distance:     distance,
                ElapsedTime:  int32(endTime.Sub(startTime).Seconds()),
            })
        }
        if err != nil {
            return err
        }
        pointCount++
        for _, feature := range s.savedFeatures {
            if proto.Equal(feature.Location, point) {
                featureCount++
            }
        }
        if lastPoint != nil {
            distance += calcDistance(lastPoint, point) // 計算兩個 point之間的距離
        }
        lastPoint = point
    }
}

  • 雙向流 ( stream 入參既可以Recv 也可以 Send ,每一個 recv 都會循環發送 send ,這樣就模擬了雙向的效果)
// 為了模擬流發送,他在每一個請求收到后,循環發送所有的對應
// 的值, 并且枷鎖,防止并發共享一個屬性導致出現問題
func (s *routeGuideServer) RouteChat(stream pb.RouteGuide_RouteChatServer) error {
    for {
        in, err := stream.Recv()
        if err == io.EOF {
            return nil
        }
        if err != nil {
            return err
        }
        key := serialize(in.Location)

        s.mu.Lock()
        s.routeNotes[key] = append(s.routeNotes[key], in)
        // Note: this copy prevents blocking other clients while serving this one.
        // We don't need to do a deep copy, because elements in the slice are
        // insert-only and never modified.
        rn := make([]*pb.RouteNote, len(s.routeNotes[key]))
        copy(rn, s.routeNotes[key])
        s.mu.Unlock()

        for _, note := range rn {
            if err := stream.Send(note); err != nil {
                return err
            }
        }
    }
}

客戶端
其實和服務端基本邏輯一致

  • 調用服務流:
func printFeatures(client pb.RouteGuideClient, rect *pb.Rectangle) {
    log.Printf("Looking for features within %v", rect)
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    stream, err := client.ListFeatures(ctx, rect)
    if err != nil {
        log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
    }
    for {
        feature, err := stream.Recv()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
        }
        log.Printf("Feature: name: %q, point:(%v, %v)", feature.GetName(),
            feature.GetLocation().GetLatitude(), feature.GetLocation().GetLongitude())
    }
}

就是一個簡單的 for {stream.Recv()}

下面看一個簡單的,grpc 里究竟怎么實現 rpc 協議的:

func (c *routeGuideClient) GetFeature(ctx context.Context, in *Point, opts ...grpc.CallOption) (*Feature, error) {
    out := new(Feature)
    err := c.cc.Invoke(ctx, "/routeguide.RouteGuide/GetFeature", in, out, opts...)
    if err != nil {
        return nil, err
    }
    return out, nil
}

Invoke 所在接口:

type ClientConnInterface interface {
    // Invoke performs a unary RPC and returns after the response is received
    // into reply.
    Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...CallOption) error
    // NewStream begins a streaming RPC.
    NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error)
}

這里就類似 rpc 的風格了。(呀復習一下, go rpc 的基本寫法了)

type HelloService struct {}

func (p *HelloService) Hello(request string, reply *string) error {
    *reply = "hello:" + request
    return nil
}
其中Hello方法必須滿足Go語言的RPC規則:方法只能有兩個可序
列化的參數,其中第二個參數是指針類型,并且返回一個error類
型,同時必須是公開的方法。

grpc 官方文檔: 生成代碼結構的講解

具體講講生成的 代碼(有一些名稱是固定的格式)

服務端:

對于 service Bar{ rpc Foo( client_data) returns (server_data) ; } 為例子 ( 流的話加上關鍵字 stream 修飾參數即可 )
注冊函數 RegisterBarServer 格式為 Register<service name>Server (當然你也可以自己寫注冊的函數)

func RegisterBarServer(s *grpc.Server, srv BarServer)

普通一元函數 ( 以 Foo 為例子)

Foo(context.Context, *MsgA) (*MsgB, error)
// MsgA 接受的消息, MsgB 發送的消息

服務端流:

Foo(*MsgA, <ServiceName>_FooServer) error

// MsgA   接收到的消息
//  <ServiceName>_FooServer  流接口類型   
// <Services name>_<rpc_func_name>Server

<ServiceName>_FooServer 接口定義如下 ( 所以可以使用 Send 方法了):

type <ServiceName>_FooServer interface {
    Send(*MsgB) error
    grpc.ServerStream
}

客戶端流

Foo(<ServiceName>_FooServer) error

type <ServiceName>_FooServer interface {
    SendAndClose(*MsgA) error
    Recv() (*MsgB, error)
    grpc.ServerStream
}

// 一直 Recv ,最后結束的時候發送一次消息 調用 SendAndClose  結束本次響應

// 流消息結束, Recv返回(nil, io.EOF)  

雙流

Foo(<ServiceName>_FooServer) error

type <ServiceName>_FooServer interface {
    Send(*MsgA) error
    Recv() (*MsgB, error)
    grpc.ServerStream
}


//同時首發數據  Send  和 Recv

客戶端接口

  • 一元方法:
(ctx context.Context, in *MsgA, opts ...grpc.CallOption) (*MsgB, error)

  • 服務流
Foo(ctx context.Context, in *MsgA, opts ...grpc.CallOption) (<ServiceName>_FooClient, error)
// <ServiceName>_FooClient  代表 服務端的 流對象 

type <ServiceName>_FooClient interface {
    Recv() (*MsgB, error)
    grpc.ClientStream
}
  • 客戶端流
Foo(ctx context.Context, opts ...grpc.CallOption) (<ServiceName>_FooClient, error)

// <ServiceName>_FooClient代表客戶機到服務器stream的MsgA
type <ServiceName>_FooClient interface {
    Send(*MsgA) error
    CloseAndRecv() (*MsgB, error)
    grpc.ClientStream
}
  • 雙向流
type <ServiceName>_FooClient interface {
    Send(*MsgA) error
    Recv() (*MsgB, error)
    grpc.ClientStream
}

暫時完畢。。

只有 客戶端流,才有 CloseAndRecv (客戶端) 和 SendAndClose ( 服務端只有這個,沒有 send)函數,其他的沒有這兩個函數

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,837評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,196評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,688評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,654評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,456評論 6 406
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,955評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,044評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,195評論 0 287
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,725評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,608評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,802評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,318評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,048評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,422評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,673評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,424評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,762評論 2 372

推薦閱讀更多精彩內容