grpc 服务调用例子
1.创建一个hello.proto
其实就是定义一个服务,然后后面需要实现它的接口
syntax = "proto3"
//path 表示生成的go文件的存放地址,会自动生成目录的。
//name 表示生成的go文件所属的包名
option go_package="./;hello";
package hello;
service HelloService {
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
int age = 2;
}
message HelloReply {
string time = 1;
}
2.编译
protoc --go_out=plugins=grpc:. *.proto
会在当前文件夹生成hello.pb.go
3.目录树
grpctest/
├── client
│ ├── go.mod
│ ├── go.sum
│ ├── main.go
│ └── proto
│ └── hello
│ ├── hello.pb.go
│ └── hello.proto
└── server
├── go.mod
├── go.sum
├── handler
│ └── handler.go
├── proto
│ └── hello
│ ├── hello.pb.go
│ └── hello.proto
└── service.go
4.实现并启动定义的服务
mkdir server
cd server
go mod init server
- 在server/handler/handler.go文件中定义一个结构体,然后实现刚刚的SayHello方法
package handler
import (
"context"
"fmt"
hellopb "server/proto/hello"
"time"
)
type hellosrv struct {}
func NewHelloSrv() hellopb.HelloServiceServer {
return &hellosrv{}
}
func (*hellosrv)SayHello(ctx context.Context, in *hellopb.HelloRequest) (*hellopb.HelloReply, error) {
fmt.Println("姓名:", in.Name, "年龄:", in.Age)
var time string = time.Now().String()
return &hellopb.HelloReply{Time: time}, nil
}
- 在server/service.go文件中编写启动服务
package main
import (
"fmt"
"net"
hellopb "server/proto/hello"
"server/handler"
"google.golang.org/grpc"
)
const (
PORT = ":7778"
)
func main() {
lis, err := net.Listen("tcp", PORT)
if err != nil {
fmt.Println(err)
}
grpcService := grpc.NewServer()
//注册服务
hellopb.RegisterHelloServiceServer(grpcService, handler.NewHelloSrv())
if err := grpcService.Serve(lis); err != nil {
fmt.Println(err)
}
}
- 启动服务
go run service.go
5.客户端调用服务
mkdir client
cd client
go mod init client
- 需要将上面编译生成的hello.pb.go文件copy过来先,接着在client/main.go中调用服务
package main
import (
hellopb "client/proto/hello"
"google.golang.org/grpc"
"context"
"fmt"
)
const (
ADDRESS = "127.0.0.1:7778"
)
func main() {
conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
if err != nil {
fmt.Println(err)
}
defer conn.Close()
client := hellopb.NewHelloServiceClient(conn)
resp, err := client.SayHello(context.Background(), &hellopb.HelloRequest{Name: "lubenwei", Age: "21"})
if err != nil {
fmt.Println(err)
}
fmt.Println(resp.Time)
}
- 测试一下
go run main.go
client输出:
2020-03-31 16:46:04.018755957 +0800 CST m=+5.300707152
server输出:
姓名: lubenwei 年龄: 21