补充grpc

This commit is contained in:
yumaojun03 2025-08-24 11:35:52 +08:00
parent da07118860
commit 078be130d7
7 changed files with 516 additions and 1 deletions

View File

@ -1,6 +1,6 @@
<mxfile host="65bd71144e">
<diagram id="yflk6MuM42xHFq2jSyhu" name="第 1 页">
<mxGraphModel dx="1333" dy="587" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<mxGraphModel dx="1333" dy="710" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
@ -24,6 +24,36 @@
<mxCell id="9" value="fn: (my_name) {hello, my_name}" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="350" y="250" width="230" height="30" as="geometry"/>
</mxCell>
<mxCell id="10" value="service c&lt;div&gt;python&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="630" y="390" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="11" value="service d&lt;div&gt;java&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="390" y="390" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="12" value="server b&lt;div&gt;go&lt;/div&gt;" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="150" y="390" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="19" style="edgeStyle=none;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;" edge="1" parent="1" source="13" target="16">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="20" style="edgeStyle=orthogonalEdgeStyle;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;" edge="1" parent="1" source="13" target="17">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="13" value="protofuf" style="rounded=0;whiteSpace=wrap;html=1;" vertex="1" parent="1">
<mxGeometry x="390" y="570" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="15" value="interface(struct)" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="160" y="480" width="100" height="30" as="geometry"/>
</mxCell>
<mxCell id="16" value="interface(class)" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="400" y="480" width="100" height="30" as="geometry"/>
</mxCell>
<mxCell id="17" value="class" style="text;html=1;align=center;verticalAlign=middle;whiteSpace=wrap;rounded=0;" vertex="1" parent="1">
<mxGeometry x="670" y="480" width="60" height="30" as="geometry"/>
</mxCell>
<mxCell id="18" style="edgeStyle=orthogonalEdgeStyle;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.43;entryY=1;entryDx=0;entryDy=0;entryPerimeter=0;" edge="1" parent="1" source="13" target="15">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>

View File

@ -0,0 +1,158 @@
# protobuf
```go
// RPC 协议,约束服务端的实现,约束 客户端的调用
type HelloService interface {
Hello(ctx context.Context, request string) (string, error)
}
```
+ RPC方法的定义
+ PRC数据结构的定义
## 插件安装
```sh
➜ protobuf go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go: downloading google.golang.org/protobuf v1.36.8
➜ protobuf go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go: downloading google.golang.org/grpc v1.75.0
```
## 接口声明
```proto
syntax = "proto3";
package hello;
option go_package="122.51.31.227/go-course/go18/skills/rpc/protobuf/hello_service";
// The HelloService service definition.
service HelloService {
// rpc 声明接口
rpc Hello (Request) returns (Response);
}
message Request {
string value = 1;
}
message Response {
string value = 1;
}
```
## 使用protobuf 定义数据结构
使用protoc-gen-go 插件来生成struct
```proto
message Request {
string value = 1;
}
message Response {
string value = 1;
}
```
```sh
# -- go_out 是参数, go out: go使用go语言插件(protoc-gen-go), go语言插件的参数 out
# out: 生成的代码放哪个目录, 默认项目根目录
# opt: module="xxx", 用于指定文件所属go module
# 应用使用了module="xxx"最好在工程根目录执行
# -I: 指定protobuf include的其他包的搜索位置, 通常情况 项目根目录比较合适
# cd go18
protoc -I=. --go_out=. --go_opt=module="122.51.31.227/go-course/go18" skills/rpc/protobuf/hello_service/interface.proto
```
interface.pb.go
```go
type Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
type Response struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
```
## 使用protobuf 定义RPC (grpc)
使用 protoc-gen-go-grpc来生成 接口描述(service定义相关部分)
```proto
// The HelloService service definition.
service HelloService {
// rpc 声明接口
rpc Hello (Request) returns (Response);
}
```
```sh
# -- go_out 是参数, go out: go使用go语言插件(protoc-gen-go), go语言插件的参数 out
# out: 生成的代码放哪个目录, 默认项目根目录
# opt: module="xxx", 用于指定文件所属go module
# 应用使用了module="xxx"最好在工程根目录执行
# -I: 指定protobuf include的其他包的搜索位置, 通常情况 项目根目录比较合适
# cd go18
protoc -I=. --go-grpc_out=. --go-grpc_opt=module="122.51.31.227/go-course/go18" skills/rpc/protobuf/hello_service/interface.proto
```
interface_grpc.pb.go
```go
// 服务端接口
// HelloServiceServer is the server API for HelloService service.
// All implementations must embed UnimplementedHelloServiceServer
// for forward compatibility.
//
// The HelloService service definition.
type HelloServiceServer interface {
// rpc 声明接口
Hello(context.Context, *Request) (*Response, error)
mustEmbedUnimplementedHelloServiceServer()
}
// 客户端接口
// HelloServiceClient is the client API for HelloService 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.
//
// The HelloService service definition.
type HelloServiceClient interface {
// rpc 声明接口
Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}
// 客户端的具体实现
type helloServiceClient struct {
cc grpc.ClientConnInterface
}
func NewHelloServiceClient(cc grpc.ClientConnInterface) HelloServiceClient {
return &helloServiceClient{cc}
}
func (c *helloServiceClient) Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(Response)
err := c.cc.Invoke(ctx, HelloService_Hello_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
```
## 服务端实现接口注册给grpc服务
## 其他服务 使用生成的client调用grpc服务的方法

View File

@ -0,0 +1,173 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.8
// protoc v6.32.0
// source: skills/rpc/protobuf/hello_service/interface.proto
package hello_service
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type Request struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Request) Reset() {
*x = Request{}
mi := &file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Request) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Request) ProtoMessage() {}
func (x *Request) ProtoReflect() protoreflect.Message {
mi := &file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Request.ProtoReflect.Descriptor instead.
func (*Request) Descriptor() ([]byte, []int) {
return file_skills_rpc_protobuf_hello_service_interface_proto_rawDescGZIP(), []int{0}
}
func (x *Request) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
type Response struct {
state protoimpl.MessageState `protogen:"open.v1"`
Value string `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Response) Reset() {
*x = Response{}
mi := &file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *Response) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*Response) ProtoMessage() {}
func (x *Response) ProtoReflect() protoreflect.Message {
mi := &file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use Response.ProtoReflect.Descriptor instead.
func (*Response) Descriptor() ([]byte, []int) {
return file_skills_rpc_protobuf_hello_service_interface_proto_rawDescGZIP(), []int{1}
}
func (x *Response) GetValue() string {
if x != nil {
return x.Value
}
return ""
}
var File_skills_rpc_protobuf_hello_service_interface_proto protoreflect.FileDescriptor
const file_skills_rpc_protobuf_hello_service_interface_proto_rawDesc = "" +
"\n" +
"1skills/rpc/protobuf/hello_service/interface.proto\x12\x05hello\"\x1f\n" +
"\aRequest\x12\x14\n" +
"\x05value\x18\x01 \x01(\tR\x05value\" \n" +
"\bResponse\x12\x14\n" +
"\x05value\x18\x01 \x01(\tR\x05value28\n" +
"\fHelloService\x12(\n" +
"\x05Hello\x12\x0e.hello.Request\x1a\x0f.hello.ResponseB@Z>122.51.31.227/go-course/go18/skills/rpc/protobuf/hello_serviceb\x06proto3"
var (
file_skills_rpc_protobuf_hello_service_interface_proto_rawDescOnce sync.Once
file_skills_rpc_protobuf_hello_service_interface_proto_rawDescData []byte
)
func file_skills_rpc_protobuf_hello_service_interface_proto_rawDescGZIP() []byte {
file_skills_rpc_protobuf_hello_service_interface_proto_rawDescOnce.Do(func() {
file_skills_rpc_protobuf_hello_service_interface_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_skills_rpc_protobuf_hello_service_interface_proto_rawDesc), len(file_skills_rpc_protobuf_hello_service_interface_proto_rawDesc)))
})
return file_skills_rpc_protobuf_hello_service_interface_proto_rawDescData
}
var file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_skills_rpc_protobuf_hello_service_interface_proto_goTypes = []any{
(*Request)(nil), // 0: hello.Request
(*Response)(nil), // 1: hello.Response
}
var file_skills_rpc_protobuf_hello_service_interface_proto_depIdxs = []int32{
0, // 0: hello.HelloService.Hello:input_type -> hello.Request
1, // 1: hello.HelloService.Hello:output_type -> hello.Response
1, // [1:2] is the sub-list for method output_type
0, // [0:1] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_skills_rpc_protobuf_hello_service_interface_proto_init() }
func file_skills_rpc_protobuf_hello_service_interface_proto_init() {
if File_skills_rpc_protobuf_hello_service_interface_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_skills_rpc_protobuf_hello_service_interface_proto_rawDesc), len(file_skills_rpc_protobuf_hello_service_interface_proto_rawDesc)),
NumEnums: 0,
NumMessages: 2,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_skills_rpc_protobuf_hello_service_interface_proto_goTypes,
DependencyIndexes: file_skills_rpc_protobuf_hello_service_interface_proto_depIdxs,
MessageInfos: file_skills_rpc_protobuf_hello_service_interface_proto_msgTypes,
}.Build()
File_skills_rpc_protobuf_hello_service_interface_proto = out.File
file_skills_rpc_protobuf_hello_service_interface_proto_goTypes = nil
file_skills_rpc_protobuf_hello_service_interface_proto_depIdxs = nil
}

View File

@ -0,0 +1,18 @@
syntax = "proto3";
package hello;
option go_package="122.51.31.227/go-course/go18/skills/rpc/protobuf/hello_service";
// The HelloService service definition.
service HelloService {
// rpc
rpc Hello (Request) returns (Response);
}
message Request {
string value = 1;
}
message Response {
string value = 1;
}

View File

@ -0,0 +1,128 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v6.32.0
// source: skills/rpc/protobuf/hello_service/interface.proto
package hello_service
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 (
HelloService_Hello_FullMethodName = "/hello.HelloService/Hello"
)
// HelloServiceClient is the client API for HelloService 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.
//
// The HelloService service definition.
type HelloServiceClient interface {
// rpc 声明接口
Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error)
}
type helloServiceClient struct {
cc grpc.ClientConnInterface
}
func NewHelloServiceClient(cc grpc.ClientConnInterface) HelloServiceClient {
return &helloServiceClient{cc}
}
func (c *helloServiceClient) Hello(ctx context.Context, in *Request, opts ...grpc.CallOption) (*Response, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(Response)
err := c.cc.Invoke(ctx, HelloService_Hello_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// HelloServiceServer is the server API for HelloService service.
// All implementations must embed UnimplementedHelloServiceServer
// for forward compatibility.
//
// The HelloService service definition.
type HelloServiceServer interface {
// rpc 声明接口
Hello(context.Context, *Request) (*Response, error)
mustEmbedUnimplementedHelloServiceServer()
}
// UnimplementedHelloServiceServer 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 UnimplementedHelloServiceServer struct{}
func (UnimplementedHelloServiceServer) Hello(context.Context, *Request) (*Response, error) {
return nil, status.Errorf(codes.Unimplemented, "method Hello not implemented")
}
func (UnimplementedHelloServiceServer) mustEmbedUnimplementedHelloServiceServer() {}
func (UnimplementedHelloServiceServer) testEmbeddedByValue() {}
// UnsafeHelloServiceServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to HelloServiceServer will
// result in compilation errors.
type UnsafeHelloServiceServer interface {
mustEmbedUnimplementedHelloServiceServer()
}
func RegisterHelloServiceServer(s grpc.ServiceRegistrar, srv HelloServiceServer) {
// If the following call pancis, it indicates UnimplementedHelloServiceServer 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(&HelloService_ServiceDesc, srv)
}
func _HelloService_Hello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(Request)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(HelloServiceServer).Hello(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: HelloService_Hello_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(HelloServiceServer).Hello(ctx, req.(*Request))
}
return interceptor(ctx, in, info, handler)
}
// HelloService_ServiceDesc is the grpc.ServiceDesc for HelloService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var HelloService_ServiceDesc = grpc.ServiceDesc{
ServiceName: "hello.HelloService",
HandlerType: (*HelloServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Hello",
Handler: _HelloService_Hello_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "skills/rpc/protobuf/hello_service/interface.proto",
}

View File

@ -0,0 +1,3 @@
package main
func main() {}

View File

@ -0,0 +1,5 @@
package main
func main() {
}