nexus-go
安装
安装protoc-gen-go
go install github.com/golang/protobuf/protoc-gen-go
安装 protoc-gen-nexus
go install github.com/stephenfaust/nexus-go/protoc-gen-nexus
快速开始
在项目引入nexus-go
go get github.com/stephenfaust/nexus-go
创建一个protobuf文件 test.proto
syntax = "proto3";
package message;
option go_package = "/message";
// this is description
service TestQueryService{
rpc GetUserById(UserReq) returns (User);
rpc ListUserByIds(ListUserReq) returns(UserResp);
}
message UserReq{
int64 id = 1;
}
message ListUserReq{
repeated int64 ids = 1;
}
message UserResp{
repeated User users = 1;
}
message User{
string name = 1;
int32 age = 2;
int32 gender = 3;
}
服务端
protoc --nexus_out=gen-ser=true:. --go_out=. test.proto
// Code generated by protoc-gen-nexus.
package message
import (
"github.com/StephenFaust/nexus-go/nexus"
"reflect"
)
// TestQueryService this is description
type TestQueryService struct{}
func (s *TestQueryService) GetUserById(args *UserReq, reply *User) error {
// define your service ...
return nil
}
func (s *TestQueryService) ListUserByIds(args *ListUserReq, reply *UserResp) error {
// define your service ...
return nil
}
// GetTestQueryServiceInfo method generated by protoc-gen-nexus.
func GetTestQueryServiceInfo() nexus.ServiceInfo {
service := &TestQueryService{}
serviceType := reflect.TypeOf(service)
methodMap := make(map[string]*nexus.MethodInfo)
for i := 0; i < serviceType.NumMethod(); i++ {
method := serviceType.Method(i)
methodMap[method.Name] = &nexus.MethodInfo{
Method: method,
ParType: method.Type.In(1),
RelyType: method.Type.In(2),
}
}
return nexus.ServiceInfo{
Name: "TestQueryService",
Value: reflect.ValueOf(service),
Methods: methodMap,
}
}
func StartNexus() {
err := nexus.StartServer(1234,
message.GetTestQueryServiceInfo())
if err != nil {
log.Fatal("Nexus server start failed,", err)
}
}
客户端
protoc --nexus_out=gen-cli=true:. --go_out=. test.proto
// Code generated by protoc-gen-nexus.
package message
import (
"github.com/StephenFaust/nexus-go/nexus"
)
// TestQueryServiceClient this is description
type TestQueryServiceClient struct {
client *nexus.RpcClient
}
func NewTestQueryServiceClient(client *nexus.RpcClient) TestQueryServiceClient {
return TestQueryServiceClient{
client: client,
}
}
func (sc *TestQueryServiceClient) GetUserById(args *UserReq, reply *User) error {
return sc.client.Invoke(args, "TestQueryService", "GetUserById", reply)
}
func (sc *TestQueryServiceClient) ListUserByIds(args *ListUserReq, reply *UserResp) error {
return sc.client.Invoke(args, "TestQueryService", "ListUserByIds", reply)
}
client := nexus.NewClient("127.0.0.1:1234", 4)
serviceClient := message.NewTestQueryServiceClient(client)
req := &message.UserReq{
Id: 1,
}
resp := new(message.User)
err := serviceClient.GetUserById(req, resp)