linux下golang gRPC構成の詳細


1.gRPC運転環境のインストール
go get google.golang.org/grpc

ここのgrpcは通俗的にコードに使われるクラスライブラリであり,後の例で見ることができる.比较坑的是ここにFQが必要かもしれない.....
2.protocのインストール
ここにはproto bufferのコンパイラを取り付ける必要があります.まず、c++バージョンのprotobuf-cpp-3.4などの公式サイトでダウンロードします.1.tar.gz、解凍してコンパイルする:
./configure         
make && make install

3.protoc-gen-goのインストール
go get -a github.com/golang/protobuf/protoc-gen-go

4.protoファイルの作成
protobufの言語間特性に基づいて、独自にデータ型を実現したと考えられます.ここには簡単な例があります
//testHello.proto
syntax = "proto3";

package protos;

// The service definition.
service Devops {
    //     
    rpc SayHello (HelloRequest) returns (Response) {}
}

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

// The response message
message HelloReply {
    string message = 1;
}

message Response {
    enum StatusCode {
        UNDEFINED = 0;
        SUCCESS = 200;
        FAILURE = 500;
    }
    StatusCode status = 1;
    HelloReply msg = 2;
}

そして端末で自動的にpbを生成する.go:
protoc --go_out=plugins=grpc:. testHello.proto

5.サービス側の作成
package main

const (
    port = ":50051"
)

type myserver struct{}

//  myserver   SayHello
func (s *myserver) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.Response, error) {
    fmt.Print("receive " + in.Name)
    return &pb.Response{
        Status:pb.Response_SUCCESS,
        Msg:&pb.HelloReply{Message:"receive " + in.Name},
    }, nil
}

func main() {
    //    
    lis, err := net.Listen("tcp", port)
    if err != nil{
        log.Fatal("fail to listen")
    }

    s := grpc.NewServer()
    pb.RegisterDevopsServer(s, &myserver{})
    s.Serve(lis)
}

6.クライアントの作成
package main

const (
    address = "localhost:50051"
)

func main()  {
   //grpc.WithInsecure()        
    conn, err := grpc.Dial(address, grpc.WithInsecure())

    if err != nil{
        log.Fatal("error....", err)
    }
    c := pb.NewDevopsClient(conn)
    res, _ := c.SayHello(context.Background(), &pb.HelloRequest{"eeee"})

    fmt.Print(res)
}

WithInsecure returns a DialOption which disables transport security for this ClientConn. Note that transport security is required unless WithInsecure is set.
WithInsecureは、転送中にセキュリティが保証されていないDialOptionを返します.WithInsecureを設定しない限りgrpc.Dialはセキュリティオプションを指定する必要があります.
参照先:
1.https://github.com/google/protobuf/releases 2.http://www.cnblogs.com/YaoDD/p/5504881.html
転載先:https://www.cnblogs.com/xiaodeshan/p/7794874.html