pb

ad.proto

  1. // 指定 proto 的版本信息
  2. syntax = "proto3";
  3. // 指定生成的 go 文件存放位置及其包名
  4. option go_package = "./;pb";
  5. // 指定所在包的包名
  6. package pb;
  7. // 导入包,注意:这么指定的导入方式,需要 protoc 命令在文件所在目录中执行编译操作
  8. import "manager.proto";
  9. // 定义商品类型的枚举消息体
  10. enum BrandType {
  11. General = 0;
  12. Standard = 1;
  13. }
  14. // 定义请求消息体
  15. message GetBrandInfoReq {
  16. int64 brand_id = 1;
  17. }
  18. // 定义响应消息体
  19. message GetBrandInfoRsp {
  20. int64 brand_id = 1;
  21. string brand_name = 2;
  22. repeated int64 brand_adv_list = 3;
  23. Manager manager = 4;
  24. BrandType brand_type = 5;
  25. }
  26. // 定义 rpc 服务
  27. service AdService {
  28. // 获取商品信息接口
  29. rpc GetBrandInfo(GetBrandInfoReq) returns (GetBrandInfoRsp);
  30. }

manager.proto

  1. // 指定 proto 的版本信息
  2. syntax = "proto3";
  3. // 指定生成的 go 文件存放位置及其包名
  4. option go_package = "./;pb";
  5. // 指定所在包的包名
  6. package pb;
  7. message Manager {
  8. int64 user_id = 1;
  9. string user_name =2;
  10. }

protoc —go_out=../service/ server1.proto
protoc —go-grpc_out=../service/ server1.proto


服务端demo

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "go_study/grpc/pb"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/credentials"
  8. "net"
  9. "xiangmu/go_gateway-master/go_gateway/golang_common/log"
  10. )
  11. type AdService struct {
  12. }
  13. func (this *AdService) GetBrandInfo(ctx context.Context, req *pb.GetBrandInfoReq) (*pb.GetBrandInfoRsp,err error) {
  14. if req.BrandId == 10 {
  15. return &pb.GetBrandInfoRsp{BrandID: 10 ,BrandName: "ad"},nil
  16. }else {
  17. return &pb.GetBrandInfoRsp{BrandID: req.BrandId ,BrandName: "other"},nil
  18. }
  19. }
  20. func main() {
  21. grpcServer := grpc.NewServer()
  22. pb.RegisterAdServiceServer(grpcServer,new(AdService))
  23. listen,err := net.Listen("tcp","121.0.0.1:8088")
  24. if err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. defer listen.Close()
  29. grpcServer.Serve(listen)
  30. }

客户端demo

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "go_study/grpc/pb"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/credentials/insecure"
  8. )
  9. func main() {
  10. // 1 创建客户端连接
  11. conn, err := grpc.Dial("127.0.0.1:8080", grpc.WithTransportCredentials(insecure.NewCredentials()))
  12. if err != nil {
  13. fmt.Println("grpc Dial err: ", err)
  14. return
  15. }
  16. defer conn.Close()
  17. // 2 创建远程服务的客户端
  18. grpcClient := pb.NewAdServiceClient(conn)
  19. req := pb.GetBrandInfoReq{BrandId: 9}
  20. // 3 发送 rpc 请求
  21. res, err := grpcClient.GetBrandInfo(context.Background(), &req)
  22. if err != nil {
  23. fmt.Println("grpcClient GetBrandInfo err: ", err)
  24. return
  25. }
  26. fmt.Println(res)
  27. }