前言
上一节讲了proto的安装和php如何使用gRPC,使用gRPC需先安装protoc工具,没看过的小伙伴先移步看上一节的内容。
本文主要讲Go如何启动gRPC服务和如何使用客户端请求gRPC。
正文
gRPC代码生成
万事say hello,本节也是从最简单的hello说起吧
新建 hello.proto
syntax = "proto3";
// 参数分号隔开,第一个是定义要创建的文件夹名称;第二个是定义包名
option go_package = "./hello;hello";
// 定义服务
service Hello {
// 定义服务方法
rpc SayHello (SayHelloRequest) returns (SayHelloReply) {}
}
// 声明参数:请求参数有name,可定义多个
message SayHelloRequest {
string name = 1;
}
// 声明参数:响应参数有message,可定义多个
message SayHelloReply {
string message = 1;
}
使用protoc生成 gRPC 代码
protoc --go_out=./server --go-grpc_out=./server protos/hello.proto
执行上面命令后,将会生成 hello.pb.go和hello_grpc.pb.go 两个文件,整体目录如下
服务端代码实现
在server/hello新建文件server.go,实现hello服务
package hello
import (
"context"
"log"
)
// 定义Server用于实现hello
type Server struct {
// 引用hello_grpc.pb.go的UnimplementedHelloServer,相当于继承
UnimplementedHelloServer
}
// 实现我们在protoc定义的SayHello
func (s *Server) SayHello(ctx context.Context, in *SayHelloRequest) (*SayHelloReply, error) {
// 获取protoc定义的请求参数中的name
log.Printf("Received: %v", in.GetName())
// 生成protoc定义的响应参数,message
return &SayHelloReply{Message: "Hello " + in.GetName()}, nil
}
在hello_grpc.pb.go能看到有定义SayHello方法,我们相当于重写这个方法。
还有像请求参数SayHelloRequest,响应参数SayHelloReply都是在hello_grpc.pb.go定义好的,我们只要引用就可以。
其实gRPC就是用proto语法定义一个服务,主要是方法,请求参数,响应参数
然后选择语言生成代码,你再根据你选择的语言去实现就可以了。
启动服务
根目录下新建start_hello.go
package main
import (
"linyc/server/hello"
"log"
"net"
"google.golang.org/grpc"
)
func main() {
// 监听50054端口
lis, err := net.Listen("tcp", "127.0.0.1:50054")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// new一个服务
s := grpc.NewServer()
// 服务注册
hello.RegisterHelloServer(s,&hello.Server{})
// 启动服务
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
执行启动服务:
客户端代码实现
根目录下新建test.go
package main
import (
"context"
"linyc/server/hello"
"log"
"os"
"time"
"google.golang.org/grpc"
)
func main() {
address := "localhost:50054" // 连接的host和端口
defaultName := "world"
// 设置连接服务
conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
// 定义客户端
c := hello.NewHelloClient(conn)
// Contact the server and print out its response.
name := defaultName
if len(os.Args) > 1 {
name = os.Args[1]
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
// 调用SayHello服务
r, err := c.SayHello(ctx, &hello.SayHelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
// 服务响应参数
log.Printf("Greeting: %s", r.GetMessage())
}
执行试下