ad.proto
// 指定 proto 的版本信息
syntax = "proto3";
// 指定生成的 go 文件存放位置及其包名
option go_package = "./;pb";
// 指定所在包的包名
package pb;
// 导入包,注意:这么指定的导入方式,需要 protoc 命令在文件所在目录中执行编译操作
import "manager.proto";
// 定义商品类型的枚举消息体
enum BrandType {
General = 0;
Standard = 1;
}
// 定义请求消息体
message GetBrandInfoReq {
int64 brand_id = 1;
}
// 定义响应消息体
message GetBrandInfoRsp {
int64 brand_id = 1;
string brand_name = 2;
repeated int64 brand_adv_list = 3;
Manager manager = 4;
BrandType brand_type = 5;
}
// 定义 rpc 服务
service AdService {
// 获取商品信息接口
rpc GetBrandInfo(GetBrandInfoReq) returns (GetBrandInfoRsp);
}
manager.proto
// 指定 proto 的版本信息
syntax = "proto3";
// 指定生成的 go 文件存放位置及其包名
option go_package = "./;pb";
// 指定所在包的包名
package pb;
message Manager {
int64 user_id = 1;
string user_name =2;
}
protoc —go_out=../service/ server1.proto
protoc —go-grpc_out=../service/ server1.proto
服务端demo
package main
import (
"context"
"fmt"
"go_study/grpc/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"net"
"xiangmu/go_gateway-master/go_gateway/golang_common/log"
)
type AdService struct {
}
func (this *AdService) GetBrandInfo(ctx context.Context, req *pb.GetBrandInfoReq) (*pb.GetBrandInfoRsp,err error) {
if req.BrandId == 10 {
return &pb.GetBrandInfoRsp{BrandID: 10 ,BrandName: "ad"},nil
}else {
return &pb.GetBrandInfoRsp{BrandID: req.BrandId ,BrandName: "other"},nil
}
}
func main() {
grpcServer := grpc.NewServer()
pb.RegisterAdServiceServer(grpcServer,new(AdService))
listen,err := net.Listen("tcp","121.0.0.1:8088")
if err != nil {
fmt.Println(err)
return
}
defer listen.Close()
grpcServer.Serve(listen)
}
客户端demo
package main
import (
"context"
"fmt"
"go_study/grpc/pb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
func main() {
// 1 创建客户端连接
conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
fmt.Println("grpc Dial err: ", err)
return
}
defer conn.Close()
// 2 创建远程服务的客户端
grpcClient := pb.NewAdServiceClient(conn)
req := pb.GetBrandInfoReq{BrandId: 9}
// 3 发送 rpc 请求
res, err := grpcClient.GetBrandInfo(context.Background(), &req)
if err != nil {
fmt.Println("grpcClient GetBrandInfo err: ", err)
return
}
fmt.Println(res)
}