what grpc
gRPC is a modern open source high performance RPC framework that can run in any environment. It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking and authentication. It is also applicable in last mile of distributed computing to connect devices, mobile applications and browsers to backend services.
go获取grpc依赖
go get google.golang.org/grpc
入门示例
1.编写.proto描述文件
hello.proto
syntax = "proto3";
package proto;
message String {
string value = 1;
}
service HelloService {
rpc Hello (String) returns (String);
}
2.使用protoc工具生成相应的go代码
生成的代码与porto描述文件在同一个目录下,包路径与package对应,文件名为hello.pb.go
3.服务提供者实现定义的rpc方法
package proto
import (
"context"
"fmt"
)
type HelloServiceImpl struct {
}
func (p *HelloServiceImpl) Hello(ctx context.Context, args *String) (*String, error) {
reply := &String{
Value: "hello grpc"}
return reply, nil
}
4.注册grpc服务
package main
import (
"google.golang.org/grpc"
proto "let_me_go/protobuf"
"log"
"net"
)
func main() {
// 启动一个grpc server
grpcServer := grpc.NewServer()
// 绑定服务实现,RegisterHelloServiceServer由protoc根据描述文件生成
proto.RegisterHelloServiceServer(grpcServer, new(proto.HelloServiceImpl))
listen, e := net.Listen("tcp", "localhost:8888")
if e != nil {
log.Fatal(e)
}
// 绑定监听端口
grpcServer.Serve(listen)
}
5.服务端调用grpc服务
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
proto "let_me_go/protobuf"
)
func main() {
// 监听服务提供端口
dialConn, _ := grpc.Dial("localhost:8888", grpc.WithInsecure())
defer dialConn.Close()
// 在监听端口的基础上创建grpc client,NewHelloServiceClient由protoc生成
client := proto.NewHelloServiceClient(dialConn)
// 调用rpc方法
result, _ := client.Hello(context