grpc在golang中的应用记录
1.安装protobuf,这玩意是个跨多种编程语言的序列号反序列化的东西,也负责数据传输,用的是http2,效率比spring cloud的restful 调用要高得多
https://github.com/protocolbuffers/protobuf/releases
里面有细分多种编程语言的版本,建议直接下载all的那个使用,我下载的是protobuf-all-3.7.0-rc-3.zip
下载后将bin\protoc.exe解压缩出来,放到PATH搜索路径能找到的地方,比如放到c:\windows目录里面
2.下载golang开发grpc需要用到的东西
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
go get -u google.golang.org/grpc
因为网的原因,我是从别的地方下载回来的,后续通过go install github.com/golang/protobuf/protoc-gen-go来编译生成protoc-gen-go.exe并自动安装到%GOPATH%\bin里面的
3.编写.proto rpc接口声明文件
syntax = "proto3"; //protobuf3协议
package proto;
//请求
message UserRq {
int32 id = 1;
}
//响应
message UserRp {
string name = 1;
}
//服务
service Data {
rpc GetUser(UserRq) returns (UserRp);
}
将以上内容存盘为HelloWorld.proto文件以后,通过执行以下命令生成.go文件
protoc --go_out=plugins=grpc:. HelloWorld.proto
以下为生成的结果,生成出来一个HelloWorld.pb.go文件,如下图

,然后编写grpc的server端代码,如下
package main
import (
"golang.org/x/net/context"
"google.golang.org/grpc"
"log"
"motorway/proto"
"net"
"runtime"
"strconv"
)
const (
port = "41005"
)
type Data struct{}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
//起服务
lis, err := net.Listen("tcp", ":"+port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
proto.RegisterDataServer(s, &Data{})
log.Printf("grpc server in: %s", port)
s.Serve(lis)
}
// 定义方法
func (t *Data) GetUser(ctx context.Context, request *proto.UserRq) (response *proto.UserRp, err error) {
response = &proto.UserRp{
Name: strconv.Itoa(int(request.Id)) + ":test",
}
return response, err
}
然后是编写调用的客户端程序代码,如下:
package main
import (
"fmt"
"motorway/proto"
"log"
"runtime"
"strconv"
"strings"
"sync"
"time"
"math/rand"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
var (
wg sync.WaitGroup
)
const (
networkType = "tcp"
server = "172.0.16.105"//"127.0.0.1"
port = "41005"
parallel = 5 //连接并行度
times = 10 //每连接请求次数
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
currTime := time.Now()
//并行请求
for i := 0; i < int(parallel); i++ {
wg.Add(1)
go func() {
defer wg.Done()
exe()
}()
}
wg.Wait()
log.Printf("time taken: %.2f s ", time.Now().Sub(currTime).Seconds())
}
func exe() {
//建立连接
conn, err := grpc.Dial(server + ":" + port,grpc.WithInsecure())
if nil!=conn{
defer conn.Close()
}
if (nil!=err){
fmt.Printf("创建连接失败!%s\n",err)
return
}
client := proto.NewDataClient(conn)
for i := 0; i < int(times); i++ {
getUser(client)
}
}
func getUser(client proto.DataClient) {
var request proto.UserRq
r := rand.Intn(parallel)
request.Id = int32(r)
response, _ := client.GetUser(context.Background(), &request) //调用远程方法
id, err:= strconv.Atoi(strings.Split(response.Name, ":")[0]);
if err!=nil{
fmt.Printf("error %s \n",err)
return
}
//判断返回结果是否正确
if id != r {
log.Printf("response error %#v", response)
}
}
实地在外地出差的网络环境下,通过v那个p那个n连接单位的机器做grpc远程调用,500次调用在1s左右,瓶颈应该在网络方面,再尝试多调用几次v那个p那个n就断掉了,本机调用本机5万次耗时3.84s,如下图:
