使用枚举、获取分区商品库存
syntax = "proto3";
package services;
import "google/api/annotations.proto";
message ProdRequest {
int32 prod_id = 1; //传入id
}
message ProdResponse {
int32 prod_stock = 1; //商品库存
}
message QuerySize {
int32 size = 1; //页尺寸,这里的1并不是默认值,而是字段的顺序,如果有其他参数就就写2
}
message ProdResponseList {
repeated ProdResponse prodres = 1; //返回了一堆商品库存,使用了repeated修饰符
}
enum ProdAreas { //定义了枚举
A = 0;
B = 1;
C = 2;
}
message ProdRequest2 {
int32 pro_id = 1; //传入的商品id
ProdAreas prod_area = 2;
}
service ProdService {
rpc GetProdStock (ProdRequest) returns (ProdResponse) {
option (google.api.http) = {
get: "/v1/prod/{prod_id}" //和request中的prod_id对应,不能写错
};
}
rpc GetProdStock2 (ProdRequest2) returns (ProdResponse) {
option (google.api.http) = {
get: "/v1/prod/{prod_id}" //和request中的prod_id对应,不能写错
};
}
rpc GetProdStocks (QuerySize) returns (ProdResponseList); //定义了参数是QuerySize
}
service中具体方法的定义
func (this *ProdService) GetProdStock2(ctx context.Context, request2 *ProdRequest2) (*ProdResponse, error) {
var stock int32 = 0
if request2.ProdArea == ProdAreas_A { //判断传递过来的枚举值是哪一个再做出相应的判断
stock = 30
} else if request2.ProdArea == ProdAreas_B {
stock = 31
} else {
stock = 50
}
return &ProdResponse{ProdStock: stock}, nil
}
客户端调用
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"grpccli/helper"
"grpccli/services"
"log"
)
func main() {
//creds, err := credentials.NewClientTLSFromFile("keys/server.crt", "localhost")
//if err != nil {
// log.Fatal(err)+
//}
creds := helper.GetClientCreds()
conn, err := grpc.Dial(":8081", grpc.WithTransportCredentials(creds))
if err != nil {
log.Fatal(err)
}
defer conn.Close()
prodClient := services.NewProdServiceClient(conn)
response, err := prodClient.GetProdStock2(context.Background(), &services.ProdRequest2{ProId: 22, ProdArea: services.ProdAreas_B})
if err != nil {
log.Fatal(err)
}
fmt.Println(response.ProdStock)
}