grpc从安装到实现小demo
这一个使用grpc的教程,从安装到实现小demo。
安装grpc插件
使用linux
环境,语言使用golang;
官网:https://grpc.io/docs/languages/go/quickstart/
-
go plugins 安装
go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.28 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
二进制文件会下载到
GOPATH
文件夹下面的bin
文件夹中,使用go env GOPATH
可查看GOPATH
文件夹具体路径。 -
将可执行文件加入
PATH
中,这样就可以在任意目录调用protoc
命令。-
修改
~/.bashrc
文件vim ~/.bashrc # 在最后一行插入 export PATH="$PATH:$(go env GOPATH)/bin"
-
检查加入
PATH
是否成功echo $PATH # or protoc --version
-
如果没有成功,尝试调用下面命令
source ~/.bashrc
-
代码
代码结构:
proto文件
syntax = "proto3";
option go_package = "github.com/boyane126/iam/pb/student";
package student;
service Student {
rpc GetName (NameRequest) returns (StudentReply){}
}
message NameRequest{
int64 id = 1;
}
message StudentReply {
int64 id = 1;
string name = 2;
uint32 age = 3;
string class = 4;
}
编辑完成后,利用工具protoc
生成代码。
#!/bin/bash
protoc --go_out=. --go_opt=paths=source_relative \
--go-grpc_out=. --go-grpc_opt=paths=source_relative \
pb/*
服务逻辑
package servers
import (
"context"
"log"
student "github.com/boyane126/iam/pb"
)
type StudentService struct {
student.UnimplementedStudentServer
}
func (s *StudentService) GetName(ctx context.Context, in *student.NameRequest) (*student.StudentReply, error) {
log.Println("Received: ", in.Id)
return &student.StudentReply{
Id: 10,
Name: "张三",
Age: 16,
Class: "一年级2班",
}, nil
}
服务端(server)
package main
import (
"fmt"
student "github.com/boyane126/iam/pb"
"github.com/boyane126/iam/servers"
"google.golang.org/grpc"
"log"
"net"
)
func main() {
s := grpc.NewServer()
student.RegisterStudentServer(s, new(servers.StudentService))
lis, err := net.Listen("tcp", fmt.Sprintf(":5000"))
if err != nil {
log.Fatalln(err)
}
if err := s.Serve(lis); err != nil {
log.Fatalln(err)
}
}
客户端(client)
package main
import (
"context"
student "github.com/boyane126/iam/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"log"
)
const addr = "localhost:5000"
func main() {
conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatalln(err)
}
defer conn.Close()
c := student.NewStudentClient(conn)
r, err := c.GetName(context.Background(), &student.NameRequest{
Id: 10,
})
if err != nil {
log.Println(err)
return
}
log.Println(r)
}
结果
- 运行服务端
go run cmd/server/main.go
- 运行客户端
go run cmd/client/main.go
客户端打印:
2023/05/15 11:16:10 id:10 name:"张三" age:16 class:"一年级2班"
服务端打印:
2023/05/15 11:16:29 Received: 10