gRPC配置记录

zero

go运行第一个gRPC程序

安装插件

go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1

配置环境变量

将%GOPATH%\bin添加到Path中

创建项目

项目结构

├─practice
│  │  go.mod
│  │  go.sum
│  │
│  ├─client
│  │  ├─sample_client
│  │  │      client.go
│  │
│  ├─proto
│  │  │  helloworld.proto
│  │
│  └─server
│      ├─simple_server
│      │      server.go
│

编辑helloword.proto

syntax = "proto3";

package proto;      // 包名
option go_package = '/grpc/service';    // 指定生成的go代码所存放的路径,不用提前创建

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

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

生成go代码

# 进入存放.proto路径下
cd proto
# 生成代码
protoc --go_out=. --go-grpc_out=. *.proto

# 最后一个参数为源文件

生成后的目录结构

├─practice
│  │  go.mod
│  │  go.sum
│  │
│  ├─client
│  │  ├─sample_client
│  │  │      client.go
│  │
│  ├─proto
│  │  │  helloworld.proto
│  │  │
│  │  └─grpc
│  │      └─service
│  │              helloworld.pb.go
│  │              helloworld_grpc.pb.go
│  │
│  └─server
│      ├─simple_server
│      │      server.go
│

编辑client.go

package main

import (
    "context"
    "flag"
    "google.golang.org/grpc"
    "log"
    pb "practice/proto/grpc/service"
    "time"
)

const (
    defaultName = "world"
)

var (
    addr = flag.String("addr", "localhost:50051", "the address to connect to")
    name = flag.String("name", defaultName, "Name to greet")
)

func main() {
    flag.Parse()

    // 建立连接
    conn, err := grpc.Dial(*addr, grpc.WithInsecure())
    if err != nil {
        log.Fatalf("did not connect: %v", err)
    }
    defer conn.Close()
    // 实例化client
    c := pb.NewGreeterClient(conn)

    // 调用rpc,等待同步响应
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
    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())
}

server.go

package main

import (
    "context"
    "flag"
    "fmt"
    "google.golang.org/grpc"
    "log"
    "net"
    pb "practice/proto/grpc/service"
)

var (
    port = flag.Int("port", 50051, "The server port")
)

// server is used to implement helloworld.GreeterServer.
type server struct {
    pb.UnimplementedGreeterServer
}

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

func (s *server) SayHelloAgain(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error)  {
    return &pb.HelloReply{Message: "Hello Again " + in.GetName()}, nil
}

func main() {
    flag.Parse()
    // 监听端口
    lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
    if err != nil {
        log.Fatalf("failed to listen: %v", err)
    }
    // 实例化server
    s := grpc.NewServer()
    pb.RegisterGreeterServer(s, &server{})
    log.Printf("server listening at %v", lis.Addr())
    if err := s.Serve(lis); err != nil {
        log.Fatalf("failed to serve: %v", err)
    }
}

运行

启动服务端

E:\go_workplace\src\practice>go run server/simple_server/server.go
2021/11/29 19:22:27 server listening at 127.0.0.1:50051

启动客户端

E:\go_workplace\src\practice>go run client/sample_client/client.go --name cui
2021/11/29 19:23:25 Greeting: Hellocui
阅读 528
6 声望
0 粉丝
0 条评论
6 声望
0 粉丝
文章目录
宣传栏