首先创建grpc服务原来是micro.NewService还支持http等其他访问方式,但是grpc.NewService这种方法只支持grpc访问,所以需要创建网关让其支持http访问
package main
import (
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/etcd"
"github.com/micro/go-micro/service/grpc"
"micro/Services"
"micro/ServicesImpl"
)
func main() {
//consulReg := consul.NewRegistry(registry.Addrs("localhost:8500"))
etcdReg := etcd.NewRegistry(registry.Addrs("106.12.72.181:23791"))
myservice := grpc.NewService( //原来是micro.NewService还支持http等其他访问方式,但是grpc这种方法只支持grpc访问,所以需要创建网关让其支持http访问
micro.Name("api.xiahualou.com.test"),
micro.Address(":8001"),
micro.Registry(etcdReg),
//micro.Registry(consulReg),
)
Services.RegisterTestServiceHandler(myservice.Server(), new(ServicesImpl.TestService))
myservice.Run()
}
先安装下面几个工具
因为grpc-gateway生成出来的文件会和go-micro生成的文件有几个函数会同名,所以不能放在一个package下面,所以我们把新建一个文件夹serviceGW用来放网关文件,避免冲突
cd Services/protos
protoc --micro_out=../ --go_out=../ test.proto
protoc-go-inject-tag -input=../test.pb.go
#生成网关文件
protoc --go_out=plugins=grpc:../../ServiceGW test.proto
protoc --grpc-gateway_out=logtostderr=true:../../ServiceGW test.proto
cd .. && cd ..
把生成网关文件的package改成ServiceGW,原來是Services,因为我们proto文件中定义的是Services
启动grpc服务
package main
import (
"github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/etcd"
"github.com/micro/go-micro/service/grpc"
"micro/Services"
"micro/ServicesImpl"
)
func main() {
//consulReg := consul.NewRegistry(registry.Addrs("localhost:8500"))
etcdReg := etcd.NewRegistry(registry.Addrs("106.12.72.181:23791"))
myservice := grpc.NewService(
micro.Name("api.xiahualou.com.test"),
micro.Address(":8001"),
micro.Registry(etcdReg),
//micro.Registry(consulReg),
)
Services.RegisterTestServiceHandler(myservice.Server(), new(ServicesImpl.TestService))
myservice.Run()
}
启动网关服务
package main
import (
"context"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
"log"
"micro/ServiceGW"
"net/http"
)
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
gRpcEndPoint := "localhost:8001"
mux := runtime.NewServeMux()
opts := []grpc.DialOption{grpc.WithInsecure()} //不使用证书校验
err := ServiceGW.RegisterTestServiceHandlerFromEndpoint(ctx, mux, gRpcEndPoint, opts) //gRpcEndPoint在这里的作用是当有请求来到9000端口会转发给8001端口
if err != nil {
log.Fatal(err)
}
http.ListenAndServe(":9000", mux)//通过postman访问9000端口服务会转发给8001端口的rpc服务
}
通过post使用http请求访问可以拿到结果,这里请求的url就是我们proto文件中定义好的
原文地址:https://www.cnblogs.com/hualou/p/12142153.html
时间: 2024-11-05 20:26:38