Browse Source

添加 et_rpc

dev
yfh 1 month ago
parent
commit
ecf0f09c4d
  1. 15
      et_rpc/go.mod
  2. 32
      et_rpc/go.sum
  3. 1147
      et_rpc/pb/et_rpc.pb.go
  4. 349
      et_rpc/pb/et_rpc_grpc.pb.go
  5. 124
      et_rpc/proto/et_rpc.proto
  6. 58
      et_rpc/proto/go-protobuf生成帮助.txt
  7. 22
      et_rpc/rpc.go
  8. 57
      et_rpc/rpc_test.go

15
et_rpc/go.mod

@ -0,0 +1,15 @@
module et_rpc
go 1.23.1
require (
google.golang.org/grpc v1.69.4
google.golang.org/protobuf v1.36.2
)
require (
golang.org/x/net v0.30.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 // indirect
)

32
et_rpc/go.sum

@ -0,0 +1,32 @@
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
go.opentelemetry.io/otel v1.31.0 h1:NsJcKPIW0D0H3NgzPDHmo0WW6SptzPdqg/L1zsIm2hY=
go.opentelemetry.io/otel v1.31.0/go.mod h1:O0C14Yl9FgkjqcCZAsE053C13OaddMYr/hz6clDkEJE=
go.opentelemetry.io/otel/metric v1.31.0 h1:FSErL0ATQAmYHUIzSezZibnyVlft1ybhy4ozRPcF2fE=
go.opentelemetry.io/otel/metric v1.31.0/go.mod h1:C3dEloVbLuYoX41KpmAhOqNriGbA+qqH6PQ5E5mUfnY=
go.opentelemetry.io/otel/sdk v1.31.0 h1:xLY3abVHYZ5HSfOg3l2E5LUj2Cwva5Y7yGxnSW9H5Gk=
go.opentelemetry.io/otel/sdk v1.31.0/go.mod h1:TfRbMdhvxIIr/B2N2LQW2S5v9m3gOQ/08KsbbO5BPT0=
go.opentelemetry.io/otel/sdk/metric v1.31.0 h1:i9hxxLJF/9kkvfHppyLL55aW7iIJz4JjxTeYusH7zMc=
go.opentelemetry.io/otel/sdk/metric v1.31.0/go.mod h1:CRInTMVvNhUKgSAMbKyTMxqOBC0zgyxzW55lZzX43Y8=
go.opentelemetry.io/otel/trace v1.31.0 h1:ffjsj1aRouKewfr85U2aGagJ46+MvodynlQ1HYdmJys=
go.opentelemetry.io/otel/trace v1.31.0/go.mod h1:TXZkRk7SM2ZQLtR6eoAWQFIHPvzQ06FJAsO1tJg480A=
golang.org/x/net v0.30.0 h1:AcW1SDZMkb8IpzCdQUaIq2sP4sZ4zw+55h6ynffypl4=
golang.org/x/net v0.30.0/go.mod h1:2wGyMJ5iFasEhkwi13ChkO/t1ECNC4X4eBKkVFyYFlU=
golang.org/x/sys v0.26.0 h1:KHjCJyddX0LoSTb3J+vWpupP9p0oznkqVk/IfjymZbo=
golang.org/x/sys v0.26.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM=
golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53 h1:X58yt85/IXCx0Y3ZwN6sEIKZzQtDEYaBWrDvErdXrRE=
google.golang.org/genproto/googleapis/rpc v0.0.0-20241015192408-796eee8c2d53/go.mod h1:GX3210XPVPUjJbTUbvwI8f2IpZDMZuPJWDzDuebbviI=
google.golang.org/grpc v1.69.4 h1:MF5TftSMkd8GLw/m0KM6V8CMOCY6NZ1NQDPGFgbTt4A=
google.golang.org/grpc v1.69.4/go.mod h1:vyjdE6jLBI76dgpDojsFGNaHlxdjXN9ghpnd2o7JGZ4=
google.golang.org/protobuf v1.36.2 h1:R8FeyR1/eLmkutZOM5CWghmo5itiG9z0ktFlTVLuTmU=
google.golang.org/protobuf v1.36.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=

1147
et_rpc/pb/et_rpc.pb.go

File diff suppressed because it is too large

349
et_rpc/pb/et_rpc_grpc.pb.go

@ -0,0 +1,349 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v5.26.1
// source: et_rpc.proto
package pb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
NodeService_HandleIotaData_FullMethodName = "/et_rpc.NodeService/HandleIotaData"
NodeService_HandleAggData_FullMethodName = "/et_rpc.NodeService/HandleAggData"
)
// NodeServiceClient is the client API for NodeService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// NodeService 定义
type NodeServiceClient interface {
// 处理 Iota 数据并返回节点响应
HandleIotaData(ctx context.Context, in *HandleDataRequest, opts ...grpc.CallOption) (*HandleDataResponse, error)
// 处理聚集数据并返回节点响应
HandleAggData(ctx context.Context, in *HandleDataRequest, opts ...grpc.CallOption) (*HandleDataResponse, error)
}
type nodeServiceClient struct {
cc grpc.ClientConnInterface
}
func NewNodeServiceClient(cc grpc.ClientConnInterface) NodeServiceClient {
return &nodeServiceClient{cc}
}
func (c *nodeServiceClient) HandleIotaData(ctx context.Context, in *HandleDataRequest, opts ...grpc.CallOption) (*HandleDataResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(HandleDataResponse)
err := c.cc.Invoke(ctx, NodeService_HandleIotaData_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *nodeServiceClient) HandleAggData(ctx context.Context, in *HandleDataRequest, opts ...grpc.CallOption) (*HandleDataResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(HandleDataResponse)
err := c.cc.Invoke(ctx, NodeService_HandleAggData_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// NodeServiceServer is the server API for NodeService service.
// All implementations must embed UnimplementedNodeServiceServer
// for forward compatibility.
//
// NodeService 定义
type NodeServiceServer interface {
// 处理 Iota 数据并返回节点响应
HandleIotaData(context.Context, *HandleDataRequest) (*HandleDataResponse, error)
// 处理聚集数据并返回节点响应
HandleAggData(context.Context, *HandleDataRequest) (*HandleDataResponse, error)
mustEmbedUnimplementedNodeServiceServer()
}
// UnimplementedNodeServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedNodeServiceServer struct{}
func (UnimplementedNodeServiceServer) HandleIotaData(context.Context, *HandleDataRequest) (*HandleDataResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method HandleIotaData not implemented")
}
func (UnimplementedNodeServiceServer) HandleAggData(context.Context, *HandleDataRequest) (*HandleDataResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method HandleAggData not implemented")
}
func (UnimplementedNodeServiceServer) mustEmbedUnimplementedNodeServiceServer() {}
func (UnimplementedNodeServiceServer) testEmbeddedByValue() {}
// UnsafeNodeServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to NodeServiceServer will
// result in compilation errors.
type UnsafeNodeServiceServer interface {
mustEmbedUnimplementedNodeServiceServer()
}
func RegisterNodeServiceServer(s grpc.ServiceRegistrar, srv NodeServiceServer) {
// If the following call pancis, it indicates UnimplementedNodeServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&NodeService_ServiceDesc, srv)
}
func _NodeService_HandleIotaData_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HandleDataRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(NodeServiceServer).HandleIotaData(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: NodeService_HandleIotaData_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(NodeServiceServer).HandleIotaData(ctx, req.(*HandleDataRequest))
}
return interceptor(ctx, in, info, handler)
}
func _NodeService_HandleAggData_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(HandleDataRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(NodeServiceServer).HandleAggData(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: NodeService_HandleAggData_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(NodeServiceServer).HandleAggData(ctx, req.(*HandleDataRequest))
}
return interceptor(ctx, in, info, handler)
}
// NodeService_ServiceDesc is the grpc.ServiceDesc for NodeService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var NodeService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "et_rpc.NodeService",
HandlerType: (*NodeServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "HandleIotaData",
Handler: _NodeService_HandleIotaData_Handler,
},
{
MethodName: "HandleAggData",
Handler: _NodeService_HandleAggData_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "et_rpc.proto",
}
const (
MasterService_RegisterNode_FullMethodName = "/et_rpc.MasterService/RegisterNode"
MasterService_HeartbeatNode_FullMethodName = "/et_rpc.MasterService/HeartbeatNode"
MasterService_UnregisterNode_FullMethodName = "/et_rpc.MasterService/UnregisterNode"
)
// MasterServiceClient is the client API for MasterService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// MasterService 定义
type MasterServiceClient interface {
RegisterNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error)
HeartbeatNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error)
UnregisterNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error)
}
type masterServiceClient struct {
cc grpc.ClientConnInterface
}
func NewMasterServiceClient(cc grpc.ClientConnInterface) MasterServiceClient {
return &masterServiceClient{cc}
}
func (c *masterServiceClient) RegisterNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RpcResponse)
err := c.cc.Invoke(ctx, MasterService_RegisterNode_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *masterServiceClient) HeartbeatNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RpcResponse)
err := c.cc.Invoke(ctx, MasterService_HeartbeatNode_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *masterServiceClient) UnregisterNode(ctx context.Context, in *NodeRequest, opts ...grpc.CallOption) (*RpcResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(RpcResponse)
err := c.cc.Invoke(ctx, MasterService_UnregisterNode_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// MasterServiceServer is the server API for MasterService service.
// All implementations must embed UnimplementedMasterServiceServer
// for forward compatibility.
//
// MasterService 定义
type MasterServiceServer interface {
RegisterNode(context.Context, *NodeRequest) (*RpcResponse, error)
HeartbeatNode(context.Context, *NodeRequest) (*RpcResponse, error)
UnregisterNode(context.Context, *NodeRequest) (*RpcResponse, error)
mustEmbedUnimplementedMasterServiceServer()
}
// UnimplementedMasterServiceServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedMasterServiceServer struct{}
func (UnimplementedMasterServiceServer) RegisterNode(context.Context, *NodeRequest) (*RpcResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RegisterNode not implemented")
}
func (UnimplementedMasterServiceServer) HeartbeatNode(context.Context, *NodeRequest) (*RpcResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method HeartbeatNode not implemented")
}
func (UnimplementedMasterServiceServer) UnregisterNode(context.Context, *NodeRequest) (*RpcResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UnregisterNode not implemented")
}
func (UnimplementedMasterServiceServer) mustEmbedUnimplementedMasterServiceServer() {}
func (UnimplementedMasterServiceServer) testEmbeddedByValue() {}
// UnsafeMasterServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to MasterServiceServer will
// result in compilation errors.
type UnsafeMasterServiceServer interface {
mustEmbedUnimplementedMasterServiceServer()
}
func RegisterMasterServiceServer(s grpc.ServiceRegistrar, srv MasterServiceServer) {
// If the following call pancis, it indicates UnimplementedMasterServiceServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&MasterService_ServiceDesc, srv)
}
func _MasterService_RegisterNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MasterServiceServer).RegisterNode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: MasterService_RegisterNode_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MasterServiceServer).RegisterNode(ctx, req.(*NodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _MasterService_HeartbeatNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MasterServiceServer).HeartbeatNode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: MasterService_HeartbeatNode_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MasterServiceServer).HeartbeatNode(ctx, req.(*NodeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _MasterService_UnregisterNode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(NodeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(MasterServiceServer).UnregisterNode(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: MasterService_UnregisterNode_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(MasterServiceServer).UnregisterNode(ctx, req.(*NodeRequest))
}
return interceptor(ctx, in, info, handler)
}
// MasterService_ServiceDesc is the grpc.ServiceDesc for MasterService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var MasterService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "et_rpc.MasterService",
HandlerType: (*MasterServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RegisterNode",
Handler: _MasterService_RegisterNode_Handler,
},
{
MethodName: "HeartbeatNode",
Handler: _MasterService_HeartbeatNode_Handler,
},
{
MethodName: "UnregisterNode",
Handler: _MasterService_UnregisterNode_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "et_rpc.proto",
}

124
et_rpc/proto/et_rpc.proto

@ -0,0 +1,124 @@
syntax = "proto3";
package et_rpc;
option go_package = "/pb";
message NodeArgs{
string id = 1; // ID
string addr = 2; //
int32 load = 3; //
string resource_json = 4; // 使JSON
int32 weight = 5; //
NodeState status = 6; //
RPCReplyCode err_code = 7; //
string err_message = 8; //
}
message NodeResponse {
string id = 1;
string addr = 2;
RPCReplyCode err_code = 3;
string err_message = 4;
}
message NodeRegistrationRequest {
string node_id = 1;
string node_addr = 2;
}
message NodeStatusRequest {
string node_id = 1;
}
message NodeStatusResponse {
string node_id = 1;
string status = 2; // "active", "inactive"
}
//
enum NodeState {
UNKNOWN = 0;
ACTIVE = 1;
INACTIVE = 2;
}
enum RPCReplyCode {
SUCCESS = 0;
FAILURE = 1;
}
//
message KeyValue {
string key = 1; //
double value = 2; //
}
// AggData消息
message AggData {
string date = 1; // 使protobuf的时间戳类型
int32 sensor_id = 2; // SensorId
int32 struct_id = 3; // StructId
int32 factor_id = 4; // FactorId
int32 agg_type_id = 5; //
int32 agg_method_id = 6; //
repeated KeyValue agg = 7; //
repeated KeyValue changed = 8; //
string thing_id = 9; // ThingId
}
message NodeRequest{
string id = 1;
string address = 2;
repeated string thing_ids = 3;
}
message RpcResponse {
enum Status {
SUCCESS = 0; //
FAILURE = 1; //
INVALID_ARGUMENT = 2; //
NOT_FOUND = 3; //
INTERNAL_ERROR = 4; //
//
}
Status status = 1; //
string error_message = 2; //
}
message HandleDataResponse{
enum Status {
SUCCESS = 0; //
FAILURE = 1; //
INVALID_ARGUMENT = 2; //
INTERNAL_ERROR = 4; //
//
}
string addr = 1; //
int32 load = 2; //
Status status = 3; //
string error_message = 4; //
}
message HandleDataRequest {
string id = 1;
repeated string messages = 2;
}
// NodeService
service NodeService {
// Iota
rpc HandleIotaData(HandleDataRequest) returns (HandleDataResponse);
//
rpc HandleAggData(HandleDataRequest) returns (HandleDataResponse);
}
// MasterService
service MasterService {
rpc RegisterNode(NodeRequest) returns (RpcResponse);
rpc HeartbeatNode(NodeRequest) returns (RpcResponse);
rpc UnregisterNode(NodeRequest) returns (RpcResponse);
}

58
et_rpc/proto/go-protobuf生成帮助.txt

@ -0,0 +1,58 @@
gRPC https://grpc.org.cn/docs/guides/cancellation/
go get google.golang.org/grpc
go get google.golang.org/protobuf/cmd/protoc-gen-go
go get google.golang.org/grpc/cmd/protoc-gen-go-grpc
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
生成代码出错,问题解决:
查找
go list -m all | findstr grpc
go list -m all | findstr protobuf
移除不必要的依赖
go get -u github.com/gogo/protobuf@nonego get -u github.com/golang/protobuf@none
go get -u github.com/matttproud/golang_protobuf_extensions@none
更新 go.mod
go mod tidy
重新生成代码,打开命令行执行以下命令:
cd et_rpc
protoc --proto_path=proto --go_out=./pb --go_opt=paths=source_relative --go-grpc_out=./pb --go-grpc_opt=paths=source_relative proto/*.proto
==============================================================
1. 使用 Protobuf 编译器 protoc 生成 Go 代码
基本的 Protobuf 编译指令 protoc --proto_path=IMPORT_PATH --go_out=OUTPUT_PATH --go_opt=paths=source_relative your_proto_file.proto
参数说明
--proto_path=IMPORT_PATH:指定 .proto 文件的搜索路径。可以使用多个 --proto_path 选项来指定多个路径。
--go_out=OUTPUT_PATH:指定生成的 Go 代码的输出路径。可以使用 . 表示当前目录。
--go_opt=paths=source_relative:这个选项使生成的 Go 文件的包路径与 .proto 文件的相对路径一致,通常推荐使用。
your_proto_file.proto:要编译的 .proto 文件的名称。
***** ET-GO 系统的编译指令(cd 致 et-go/et_rpc 下执行)
1) 只生成消息类型的Go代码、序列化和反序列化方法、其他辅助方法:
protoc --proto_path=proto --go_out=./pb --go_opt=paths=source_relative proto/*.proto
2)生成消息类型Go代码、序列化和反序列化方法、gRPC服务的Go代码、gRPC方法的实现:
protoc --proto_path=proto --go_out=./pb --go_opt=paths=source_relative --go-grpc_out=./pb --go-grpc_opt=paths=source_relative proto/*.proto
参数说明
--proto_path=proto:指定 .proto 文件的搜索路径为 proto 目录。
--go_out=./pb:指定生成的 Go 代码输出到 pb 目录。
--go_opt=paths=source_relative:确保生成的 Go 文件的包路径与 .proto 文件的相对路径一致。
proto/*.proto:使用通配符 *.proto 来编译 proto 目录下的所有 .proto 文件。
/et-go
├── et_rpc
│ ├── pb # 存放生成的 Go 文件
│ │ └── iota_data.pb.go # 生成的 Go 文件
│ └── proto # 存放 Protobuf 文件
│ └── iota_data.proto # IotaData Protobuf 文件
└── 其他

22
et_rpc/rpc.go

@ -0,0 +1,22 @@
package et_rpc
type RPCReplyCode int
type NodeState int
const (
NodeState_Healthy NodeState = iota
NodeState_Unhealthy
)
type NodeArgs struct {
ID string
Addr string
Load int // 节点荷载(主要为积压的数据量)
ResourceJson string // CPU\内存\硬盘 使用情况JSON
Weight int // 权重(暂时未用到)
Status NodeState // 节点状态(健康 | 不健康)
ErrCode RPCReplyCode // RPCReply_Success | RPCReply_Failure
ErrMessage string
}

57
et_rpc/rpc_test.go

@ -0,0 +1,57 @@
package et_rpc
import (
"encoding/json"
"et_rpc/pb"
"fmt"
"google.golang.org/protobuf/proto"
"log"
"testing"
)
// TestProtoJSONConversion 测试 Protobuf 和 JSON 之间的转换
func TestProtoJSONConversion(t *testing.T) {
// 创建请求
request := createHandleDataRequest()
// 序列化请求为 Protobuf 格式
data, err := proto.Marshal(request)
if err != nil {
log.Fatalf("Failed to marshal request: %v", err)
}
// 打印序列化后的数据
fmt.Println("Serialized HandleDataRequest:", data)
// 这里可以将序列化后的数据发送到 gRPC 服务
// 例如:client.HandleIotaData(context.Background(), request)
}
func createJSONData(id string, value float64) (string, error) {
data := map[string]interface{}{
"id": id,
"value": value,
}
jsonData, err := json.Marshal(data)
if err != nil {
return "", err
}
return string(jsonData), nil
}
func createHandleDataRequest() *pb.HandleDataRequest {
request := &pb.HandleDataRequest{}
// 添加 JSON 数据消息
json1, _ := createJSONData("1", 10.5)
json2, _ := createJSONData("2", 20.3)
json3, _ := createJSONData("3", 15.8)
request.Messages = append(request.Messages, json1)
request.Messages = append(request.Messages, json2)
request.Messages = append(request.Messages, json3)
return request
}
Loading…
Cancel
Save