golang grpc demo

1、安装 gRPC 和 Protobuf

protobuf 安装链接:https://liqiang.io/post/install-protobuf-in-centos-f0a9b926

protoc-gen-go 二进制构建

1
2
3
git clone https://github.com/golang/protobuf.git
cd protobuf
go build protoc-gen-go/main.go -o /bin/protoc-gen-go

2、定义.proto 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
mkdir helloworld
cd helloworld
 
#cat hello.proto
syntax = "proto3";
 
package helloworld;
 
option go_package = "./helloworld";
 
// 定义服务
service Greeter {
    // 定义方法
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
// 定义请求参数
message HelloRequest {
    string name = 1;
}
 
// 定义响应参数
message HelloReply {
    string message = 1;
}

3、生成 golang 代码

1
2
cd ..
protoc -I helloworld/ helloworld/hello.proto --go_out=plugins=grpc:helloworld

4、实现服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
cd helloworld
 
#cat server.go
package main
 
import (
    "context"
    "log"
    "net"
 
    "google.golang.org/grpc"
 
    pb "helloworld/helloworld" // 导入生成的代码
)
 
const (
    port = ":50051"
)
 
// 定义服务
type server struct {
    pb.UnimplementedGreeterServer
}
 
// 实现 SayHello 方法
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)
    }
 
    // 创建 grpc 服务
    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)
    }
}

5、实现客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#cat client.go
package main
 
import (
    "context"
    "log"
    "os"
    "time"
 
    "google.golang.org/grpc"
 
    pb "helloworld/helloworld" // 导入生成的代码
)
 
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()
 
    // 创建客户端
    c := pb.NewGreeterClient(conn)
 
    // 设置超时
    ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    defer cancel()
 
    // 构建请求
    name := defaultName
    if len(os.Args) > 1 {
        name = os.Args[1]
    }
 
    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())
}

6、运行示例

1
2
3
4
5
6
7
8
9
10
11
12
go mod init
go mod tidy
go mod vendor
 
# server
#go run server.go
2023/05/24 19:00:21 server listening at [::]:50051
2023/05/24 19:00:24 Received: world
 
# client
#go run client.go
2023/05/24 19:00:24 Greeting: Hello world

  

本文作者:salami_china

本文链接:https://www.cnblogs.com/wangjq19920210/p/17428921.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   salami_china  阅读(38)  评论(0编辑  收藏  举报
历史上的今天:
2019-05-24 Linux系列—策略路由、ip rule、ip route
2019-05-24 Open vSwitch with DPDK
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起