grpc demo
proto文件
编译命令:protoc --go_out=plugins=grpc:./ person.proto
否则 服务是不会编译进去的
安装
go get -u -v google.golang.org/grpc
syntax = "proto3";
package pb;
option go_package = "./;pb";
message Teacher{
int32 age= 1;
string name = 2;
}
service SayName{
rpc SayHello(Teacher) returns (Teacher);
}
server
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"net"
"xiaosheng/pb"
)
type Child struct {
}
// SayHello 按接口绑定类方法
func (this *Child) SayHello(ctx context.Context, teacher *pb.Teacher) (*pb.Teacher, error) {
teacher.Name += " is good!"
return teacher, nil
}
func main() {
//1. 初始一个 grpc 对象
serve := grpc.NewServer()
//2. 注册服务
pb.RegisterSayNameServer(serve, new(Child))
//3. 设置监听, 指定 IP、port
listen, err := net.Listen("tcp", "127.0.0.1:8700")
if err != nil {
fmt.Println("[*]:listen err:", err)
return
}
fmt.Println("[*]: on listening---")
//4. 启动服务。 serve()
serve.Serve(listen)
}
client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"xiaosheng/pb"
)
func main() {
//1. 连接 grpc 服务
conn, err := grpc.Dial("127.0.0.1:8700", grpc.WithInsecure())
if err != nil {
fmt.Println("Dial err:", err)
return
}
defer conn.Close()
//2. 初始化 grpc 客户端
client := pb.NewSayNameClient(conn)
//3. 调用远程服务。
// 创建并初始化一个Teacher对象
teacher := pb.Teacher{
Age: 18,
Name: "xiaog",
}
t, err := client.SayHello(context.TODO(), &teacher)
fmt.Println(t, err)
}
protobuf
基础语法
// 默认是proto2
syntax = "proto3";
// 注意加分号
// 指定所在包名,
package pb;
option go_package = "./;pb";
// 定义枚举类型
enum Week {
Sunday = 0; // 枚举值必须从 0 开始
Monday = 1;
Tuesday = 2;
Wednesday = 3;
}
// 定义消息体,类似go的struct
message Student {
int32 age = 1; // 可以补充1开始,但是不能重复
string name = 2;
bool married = 3;
// 嵌套消息体
repeated int32 score = 4; // 数组*
// 枚举
Week w = 5;
// 联合体, 从数据中任选一个
oneof data {
string teacher = 6; // 编号不能重复
string girlfriend = 7;
}
}
// 消息体可以嵌套,
message People {
int32 weight = 1;
}
// 添加一个rpc服务
service xs {
rpc Say(People) returns (Student);
}