golang-grpc

3180 ワード

1.grpcのインストール

git clone https://github.com/grpc/grpc-go.git $GOPATH/src/google.golang.org/grpc
git clone https://github.com/golang/net.git $GOPATH/src/golang.org/x/net
git clone https://github.com/golang/text.git $GOPATH/src/golang.org/x/text
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
git clone https://github.com/google/go-genproto.git $GOPATH/src/google.golang.org/genproto
 
cd $GOPATH/src/
go install google.golang.org/grpc  //            grpc,     ,cp /bin/grpc  /usr/local/bin

2.protocal buffer compilerのインストール


(1.)github上releaseバージョンダウンロードhttps://github.com/protocolbuffers/protobuf/releases/tag/v3.11.3//対応するバージョンとオペレーティングシステムを探してダウンロードし、ダウンロードした後、zipパッケージを解凍し、/bin/protocを/usr/local/binの下にコピーします(2.)あるいはソースコードを用いてインストールをコンパイルする
https://github.com/google/protobuf/releases
tar -zxvf xxxx.tar.gz
cd xxxx/
./configure
make
make install

export LD_LIBRARY_PATH=/usr/local/lib   //      

3.使用例


(1.)protoファイルの作成
syntax = "proto3";

package grpcusage;

service Hello {
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
    string Name = 1;
}

message HelloReply {
    string Message = 1;
}

(2.)golang grpcコードの生成
#   protoc --go_out=plugins=grpc:{go      } {proto  }
protoc --go_out=plugins=grpc:./ ./helloworld.proto

(3.)サービス側コードの作成
package main

import (
    "golang.org/x/net/context"
    pb "helloworld"

    "net"
    "log"
    "google.golang.org/grpc"
    "fmt"
)

const (
    port = ":50051"
)

type Server struct {}

func (s *Server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
    return &pb.HelloReply{
        Message: "hello " + in.Name,
    }, nil
}

func main() {
    conn, err := net.Listen("tcp", port)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println("grpc server listening at: 50051 port")
    server := grpc.NewServer()
    pb.RegisterHelloServer(server, &Server{})
    server.Serve(conn)
}

(4)クライアントコードの作成
package main

import (
    "google.golang.org/grpc"
    "log"
    pb "helloworld"
    "os"
    "context"
        "fmt"
)

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

func main()  {
    conn, err := grpc.Dial(address, grpc.WithInsecure())
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()
    client := pb.NewHelloClient(conn)

    name := defaultName
    if len(os.Args) > 1 {
        name = os.Args[1]
    }
    request, err := client.SayHello(context.Background(), &pb.HelloRequest{Name:name})
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(request.Message)
}

(5)サービス側とクライアントを別々に起動する
go run server.go
go run client.go

関連リンク


https://www.jianshu.com/p/e010dae6d11f https://studygolang.com/articles/15482