创建gRPC项目
go mod init grpc-demo
编写proto文件
proto语法
syntax #协议类型,目前有两套协议 proto3、proto2,推荐使用proto3,必须放在proto文件的第一行
package #包名,必须第二行
service #定义这个proto文件的方法集合,类似于方法接口
message #类似于go语言的结构体,在此定义方法的接收、返回参数
returns #返回响应,结合service使用
rpc #定义方法的关键字,结合service使用
字段操作选项
optional #结合message使用,表示message字段的内容选填,可以传也可以不传
repeated #结合message使用,表示该字段接收或返回为数组
编写实例
syntax = "proto3";
option go_package = "./;helloworld";
service HelloWorldService{
rpc SayHelloWorld(HelloRequest) returns(HelloResponse){}
}
message HelloRequest{
string Name = 1;
}
message HelloResponse{
string Msg = 1;
}
编译proto文件
protoc --go_out=plugins=grpc:./helloworld helloworld.proto
源码解析
服务端
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"grpc-test/proto/helloworld"
"net"
)
type HelloWorldService struct{}
// 提供HelloWorldService实现SayHelloWorld接口
func (hw HelloWorldService) SayHelloWorld(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloResponse, error) {
response := new(helloworld.HelloResponse)
response.Msg = fmt.Sprintf("Say HelloWorld To %s", in.Name)
return response, nil
}
func main() {
listener, e := net.Listen("tcp", "127.0.0.1:8888")
if e != nil {
fmt.Println("Listen Error",e)
return
}
helloworldService := &HelloWorldService{}
// 实例化gprc Server
server := grpc.NewServer()
// 注册服务
helloworld.RegisterHelloWorldServiceServer(server,helloworldService)
// 开启服务
server.Serve(listener);
}
客户端
package main
import (
"fmt"
"golang.org/x/net/context"
"google.golang.org/grpc"
"grpc-test/proto/helloworld"
)
func main() {
conn, e := grpc.Dial("127.0.0.1:8888", grpc.WithInsecure())
if e != nil{
fmt.Println("Connect Server Failed")
return
}
// 关闭客户端连接
defer conn.Close()
//初始化客户端
client := helloworld.NewHelloWorldServiceClient(conn)
//调用方法
response, e := client.SayHelloWorld(context.Background(), &helloworld.HelloRequest{Name: "张三"})
if e != nil{
fmt.Println("调用出错...")
return
}
message := response.Msg
fmt.Println("服务端返回:",message)
}