golang-grpc

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

猜你喜欢

转载自www.cnblogs.com/tomtellyou/p/12273628.html