RPC(四)[gRPC-Golang-環境搭建]

在這裏插入圖片描述
gRPC官方首頁:

https://grpc.io/

gRPC官方簡介:

https://grpc.io/docs/guides/

gRPC-Golang開發教程:

https://grpc.io/docs/tutorials/basic/go/

1.下載

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

因爲在go的環境變量中配置了go mod,所以要注意,且在此處下載必須是帶【/…】,否則容易報莫名的異常!

2.測試

1.服務端啓動

1.找到下載的grpc所在的目錄【使用go mod的環境變量一般在$GOPATH/pkg下面】

cd $GOPATH/pkg/mod/google.golang.org/grpc*/examples/helloworld/*_server && ls

在這裏插入圖片描述
2.啓動server服務

cd $GOPATH/pkg/mod/google.golang.org/grpc*/examples/helloworld/*_server &&  go run main.go

在這裏插入圖片描述

2.客戶端啓動

另開一個終端

1.找到下載的grpc所在的目錄【使用go mod的環境變量一般在$GOPATH/pkg下面】

cd $GOPATH/pkg/mod/google.golang.org/grpc*/examples/helloworld/*_client && ls

在這裏插入圖片描述
2.啓動client服務

cd $GOPATH/pkg/mod/google.golang.org/grpc*/examples/helloworld/*_client &&  go run main.go

在這裏插入圖片描述
環境搭建成功!!!

3.客戶端代碼淺析

/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

// Package main implements a client for Greeter service.
package main

import (
        "context"
        "log"
        "os"
        "time"

        "google.golang.org/grpc"
        pb "google.golang.org/grpc/examples/helloworld/helloworld" // 引用編譯好的protobuf文件
)

const (
        address     = "localhost:50051"
        defaultName = "world"
)

func main() {
        // 建立與服務器的連接
        conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
        if err != nil {
                log.Fatalf("did not connect: %v", err)
        }
        // 延遲關閉連接
        defer conn.Close()
        // 調用protobuf的函數創建客戶端連接句柄
        c := pb.NewGreeterClient(conn)

        // 與服務器聯繫並打印其響應。
        name := defaultName
        if len(os.Args) > 1 {
                name = os.Args[1]
        }
        // context的超時設置
        ctx, cancel := context.WithTimeout(context.Background(), time.Second)
        defer cancel()
        // 調用protobuf的SayHello函數
        r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
        if err != nil {
                log.Fatalf("could not greet: %v", err)
        }
        // 打印結果
        log.Printf("Greeting: %s", r.GetMessage())
}

4.服務端代碼淺析

/*
 *
 * Copyright 2015 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

//go:generate protoc -I ../helloworld --go_out=plugins=grpc:../helloworld ../helloworld/helloworld.proto

// Package main implements a server for Greeter service.
package main

import (
        "context"
        "log"
        "net"

        "google.golang.org/grpc"
        pb "google.golang.org/grpc/examples/helloworld/helloworld" // 引用編譯好的protobuf文件
)

const (
        port = ":50051"
)

// 服務器用於實現helloworld.GreeterServer。
type server struct {
        pb.UnimplementedGreeterServer
}

// SayHello實現helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
        log.Printf("Received: %v", in.GetName())
        return &pb.HelloReply{Message: "Hello " + in.GetName()}, nil
}

func main() {
		// 創建監聽
        lis, err := net.Listen("tcp", port)
        if err != nil {
                log.Fatalf("failed to listen: %v", err)
        }
        // new服務對象
        s := grpc.NewServer()
        // 註冊服務
        pb.RegisterGreeterServer(s, &server{})
        if err := s.Serve(lis); err != nil {
                log.Fatalf("failed to serve: %v", err)
        }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章