• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
使用gRPC-Gateway快速构建微服务-双向认证下rpc-gateway使用(同时提供rpc和http接口)

https://github.com/grpc-ecosystem/grpc-gateway

 

 

 在grpc之上加一层代理并转发,转变成protobuf格式来访问grpc服务

 

安装

go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
go get -u github.com/golang/protobuf/protoc-gen-go

 

Prod.proto

syntax="proto3";
package services;
import "google/api/annotations.proto";

message  ProdRequest {
    int32 prod_id =1;   //传入的商品ID
}
message ProdResponse{
    int32 prod_stock=1;//商品库存
}

service ProdService {
    rpc GetProdStock (ProdRequest) returns (ProdResponse){
        option (google.api.http) = {
            get: "/v1/prod/{prod_id}"
        };

    }
}

 

生成两个文件

首先cd 进入pbfiles

这会生成Prod.pb.go
protoc --go_out=plugins=grpc:../services  Prod.proto


这会生成Prod.pb.gw.go
protoc  --grpc-gateway_out=logtostderr=true:../services Prod.proto

 

httpserver.go

package main

import (
    "context"
    "github.com/grpc-ecosystem/grpc-gateway/runtime"
    "google.golang.org/grpc"
    "grpcpro/services"
    "log"
    "net/http"
)

func main()  {
    gwmux:=runtime.NewServeMux()
    opt := []grpc.DialOption{grpc.WithInsecure()}
    err:=services.RegisterProdServiceHandlerFromEndpoint(context.Background(),
        gwmux,"localhost:8081",opt)
    if err != nil {
        log.Fatal(err)
    }
    httpServer:=&http.Server{
        Addr:":8080",
        Handler:gwmux,
    }
    httpServer.ListenAndServe()

}

 

 

server.go

package main

import (
    "google.golang.org/grpc"
    "grpcpro/services"
    "net"
)

func main()  {
    rpcServer:=grpc.NewServer()
    services.RegisterProdServiceServer(rpcServer,new(services.ProdService))

    lis,_:=net.Listen("tcp",":8081")

    rpcServer.Serve(lis)


}

 

 源码地址:

https://github.com/sunlongv520/grpc-learn

https://github.com/sunlongv520/grpc-doc

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/12051719.html

posted on 2019-12-16 22:12  孙龙-程序员  阅读(1174)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3