package main import ( "context" "errors" "fmt" pro "gomicr/grpc" "net" "google.golang.org/grpc" ) // 定义个空的接口 type OrderInfoService struct{} func (order *OrderInfoService) SearchOrder(cxt context.Context, req *pro.OrderRequest) (*pro.OrderResp, error) { reqType := req.ActivityType //获取请求参数 resp := &pro.OrderResp{} fmt.Println("接收到客户端请求:", req) if reqType == 1 { //数据库操作 resp.DiscountAmount = 100 resp.Code = "200" resp.Msg = "查询成功" } else { resp.DiscountAmount = 0 resp.Code = "500" resp.Msg = "查询失败" return resp, errors.New("not found this Order!") } return resp, nil } /** 服务端 :1,开启监听 , 2,实列化GPRC服务端 3,在GRPC上注册一个微服务 4,启动服务 **/ func main() { //1,开启监听 addr := "127.0.0.1:8083" listener, err := net.Listen("tcp", addr) if err != nil { fmt.Println("监听异常:", err) } fmt.Println("服务监听端口:", addr) //2,实列化GPRC服务端 server := grpc.NewServer( //中间件切面auth logger timeout ratelimit // grpc.UnaryInterceptor() // grpc.StreamInterceptor() ) //3,在GRPC上注册一个微服务 s := OrderInfoService{} //空接口服务 pro.RegisterSearchServiceServer(server, &s) //4,启动服务 server.Serve(listener) }