protoc-gen-mqant 是一款可以自动生成rpc服务注册和调用的工具,其基于mqant微服务框架作为构建模板,通过读取Protobuffer的message和serveice构建服务注册和调用
- 下载代码到本地
git clone https://github.com/GodWY/protoc-gen-hip.git
- 执行 make {电脑型号},构建protoc-gen-mqant 可执行文件
总结: 下载代码目的是将二进制文件下载到gopath的bin文件下。
- 定义请求greeter.proto文件
syntax = "proto3";
package examples;
option go_package = "proto/examples/greeter";
message Request {
}
message Response {
}
- 定义一个rpc请求
syntax = "proto3";
package examples1;
option go_package = "proto/greeter1";
import "proto/examples/greeter.proto";
message Response {
}
service Greeter {
rpc Hello(examples.Request) returns (Response) {}
rpc Stream(examples.Request) returns ( Response) {
}
}
- 执行构建代码
protoc --plugin=protoc-gen-go=/Users/GodWY/go/bin/protoc-gen-go --go_out=./ ./proto/examples/*.proto --experimental_allow_proto3_optional
protoc --plugin=protoc-gen-mqant=protoc-gen-mqant --proto_path=. --mqant_out=./ ./proto/examples/*.proto ./proto/examples1/*.proto --experimental_allow_proto3_optional
- 生成的代码
// Code generated by protoc-gen-go-hi. DO NOT EDIT.
// versions:
package greeter1
import (
greeter "proto/examples/greeter"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the kratos package it is being compiled against.
import (
"errors"
basemodule "github.com/liangdas/mqant/module/base"
client "github.com/liangdas/mqant/module"
mqrpc "github.com/liangdas/mqant/rpc"
"golang.org/x/net/context"
)
// generated mqant method
type Greeter interface {
// @[email protected]()
Hello(in *greeter.Request) (out *Response, err error)
// @POST
Stream(in *greeter.Request) (out *Response, err error)
}
func RegisterGreeterTcpHandler(m *basemodule.BaseModule, ser Greeter) {
m.GetServer().RegisterGO("hello", ser.Hello)
m.GetServer().RegisterGO("stream", ser.Stream)
}
// generated proxxy handle
type ClientProxyService struct {
cli client.App
name string
}
func NewLoginClient(cli client.App, name string) *ClientProxyService {
return &ClientProxyService{
cli: cli,
name: name,
}
}
var ClientProxyIsNil = errors.New("proxy is nil")
func (proxy *ClientProxyService) Hello(req *greeter.Request) (rsp *Response, err error) {
if proxy == nil {
return nil, ClientProxyIsNil
}
rsp = &Response{}
err = mqrpc.Proto(rsp, func() (reply interface{}, err interface{}) {
return proxy.cli.Call(context.TODO(), proxy.name, "hello", mqrpc.Param(req))
})
return rsp, err
}
func (proxy *ClientProxyService) Stream(req *greeter.Request) (rsp *Response, err error) {
if proxy == nil {
return nil, ClientProxyIsNil
}
rsp = &Response{}
err = mqrpc.Proto(rsp, func() (reply interface{}, err interface{}) {
return proxy.cli.Call(context.TODO(), proxy.name, "stream", mqrpc.Param(req))
})
return rsp, err
}
在mqant 初始化函数里调用RegisterGreeterTcpHandler方法可以注册协议,同时如果想调用rpc协议。创建NewLoginClient代理类调用相应的rpc即可