gRPC服务的定义和服务的种类

文章目录

  • grpc服务的定义和服务的种类
    • 服务的定义
    • 服务的种类
  • grpc stream实例1-服务端单向流
    • 创建protobuf message
    • 编译
    • 生成的文件
    • 服务器端实现
    • 客户端实现
    • 运行结果
  • grpc stream实例2-客户端单向流
    • 创建protobuf message
    • 编译
    • 生成的文件
    • 服务器端实现
    • 客户端实现
    • 运行结果
  • grpc stream实例3-双向流
    • 创建protobuf message
    • 编译
    • 生成的文件
    • 服务器端实现
    • 客户端实现
    • 运行结果


grpc服务的定义和服务的种类

服务的定义

与许多RPC系统一样,gRPC基于定义服务、指定可以通过其参数和返回类型远程调用的方法的思想。默认情况下,gRPC使用protocol buffers作为接口定义语言(IDL)来描述服务接口和有效负载消息的结构。如果需要,也可以使用其他替代方案。

service HelloService {
  rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
  string greeting = 1;
}

message HelloResponse {
  string reply = 1;
}

服务的种类

gRPC 允许您定义四种服务方法:

  • 一元 RPC,其中客户端向服务器发送单个请求并获得单个响应,就像正常的函数调用一样。

    rpc SayHello(HelloRequest) returns (HelloResponse);
    
  • 服务器流式 RPC,其中客户端向服务器发送请求并获取流以读回一系列消息。客户端从返回的流中读取,直到没有更多消息为止。gRPC 保证单个 RPC 调用中的消息顺序。

    rpc LotsOfReplies(HelloRequest) returns (stream HelloResponse);
    
  • 客户端流式 RPC,其中客户端写入一系列消息并将它们发送到服务器,再次使用提供的流。一旦客户端完成了消息的写入,它就会等待服务器读取它们并返回它的响应。gRPC 再次保证了单个 RPC 调用中的消息顺序。

    rpc LotsOfGreetings(stream HelloRequest) returns (HelloResponse);
    
  • 双向流式 RPC,双方使用读写流发送一系列消息。这两个流独立运行,因此客户端和服务器可以按照他们喜欢的任何顺序读取和写入:例如,服务器可以在写入响应之前等待接收所有客户端消息,或者它可以交替读取消息然后写入消息,或其他一些读取和写入的组合。保留每个流中消息的顺序。

    rpc BidiHello(stream HelloRequest) returns (stream HelloResponse);
    

grpc stream实例1-服务端单向流

创建protobuf message

syntax = "proto3";

option go_package= "./;pb";

package pb;

service Greeter {
  // 服务端 推送流
  rpc GetStream (StreamReqData) returns (stream StreamResData){}
}

// request
message StreamReqData {
   string data = 1;
}

// response
message StreamResData {
   string data = 1;
}

编译

protoc --go_out=./pb ./pb/hello.proto
protoc --go-grpc_out=./pb ./pb/hello.proto

生成的文件

pb\hello.pb.go:

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.26.0
// 	protoc        v3.21.6
// source: pb/hello.proto

package pb

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

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)
)

// request
type StreamReqData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamReqData) Reset() {
	*x = StreamReqData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamReqData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamReqData) ProtoMessage() {}

func (x *StreamReqData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamReqData.ProtoReflect.Descriptor instead.
func (*StreamReqData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{0}
}

func (x *StreamReqData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

// response
type StreamResData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamResData) Reset() {
	*x = StreamResData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamResData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamResData) ProtoMessage() {}

func (x *StreamResData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamResData.ProtoReflect.Descriptor instead.
func (*StreamResData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{1}
}

func (x *StreamResData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

var File_pb_hello_proto protoreflect.FileDescriptor

var file_pb_hello_proto_rawDesc = []byte{
	0x0a, 0x0e, 0x70, 0x62, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x12, 0x02, 0x70, 0x62, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65,
	0x71, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20,
	0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72,
	0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
	0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x40,
	0x0a, 0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x35, 0x0a, 0x09, 0x47, 0x65, 0x74,
	0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53, 0x74, 0x72, 0x65,
	0x61, 0x6d, 0x52, 0x65, 0x71, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53,
	0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x22, 0x00, 0x30, 0x01,
	0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2f, 0x3b, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x33,
}

var (
	file_pb_hello_proto_rawDescOnce sync.Once
	file_pb_hello_proto_rawDescData = file_pb_hello_proto_rawDesc
)

func file_pb_hello_proto_rawDescGZIP() []byte {
	file_pb_hello_proto_rawDescOnce.Do(func() {
		file_pb_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_hello_proto_rawDescData)
	})
	return file_pb_hello_proto_rawDescData
}

var file_pb_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pb_hello_proto_goTypes = []interface{}{
	(*StreamReqData)(nil), // 0: pb.StreamReqData
	(*StreamResData)(nil), // 1: pb.StreamResData
}
var file_pb_hello_proto_depIdxs = []int32{
	0, // 0: pb.Greeter.GetStream:input_type -> pb.StreamReqData
	1, // 1: pb.Greeter.GetStream:output_type -> pb.StreamResData
	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_pb_hello_proto_init() }
func file_pb_hello_proto_init() {
	if File_pb_hello_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_pb_hello_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamReqData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_pb_hello_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamResData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_pb_hello_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_pb_hello_proto_goTypes,
		DependencyIndexes: file_pb_hello_proto_depIdxs,
		MessageInfos:      file_pb_hello_proto_msgTypes,
	}.Build()
	File_pb_hello_proto = out.File
	file_pb_hello_proto_rawDesc = nil
	file_pb_hello_proto_goTypes = nil
	file_pb_hello_proto_depIdxs = nil
}

pb\hello_grpc.pb.go:

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.

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.32.0 or later.
const _ = grpc.SupportPackageIsVersion7

// GreeterClient is the client API for Greeter 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.
type GreeterClient interface {
	// 服务端 推送流
	GetStream(ctx context.Context, in *StreamReqData, opts ...grpc.CallOption) (Greeter_GetStreamClient, error)
}

type greeterClient struct {
	cc grpc.ClientConnInterface
}

func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
	return &greeterClient{cc}
}

func (c *greeterClient) GetStream(ctx context.Context, in *StreamReqData, opts ...grpc.CallOption) (Greeter_GetStreamClient, error) {
	stream, err := c.cc.NewStream(ctx, &Greeter_ServiceDesc.Streams[0], "/pb.Greeter/GetStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &greeterGetStreamClient{stream}
	if err := x.ClientStream.SendMsg(in); err != nil {
		return nil, err
	}
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	return x, nil
}

type Greeter_GetStreamClient interface {
	Recv() (*StreamResData, error)
	grpc.ClientStream
}

type greeterGetStreamClient struct {
	grpc.ClientStream
}

func (x *greeterGetStreamClient) Recv() (*StreamResData, error) {
	m := new(StreamResData)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
	// 服务端 推送流
	GetStream(*StreamReqData, Greeter_GetStreamServer) error
	mustEmbedUnimplementedGreeterServer()
}

// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}

func (UnimplementedGreeterServer) GetStream(*StreamReqData, Greeter_GetStreamServer) error {
	return status.Errorf(codes.Unimplemented, "method GetStream not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}

// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
	mustEmbedUnimplementedGreeterServer()
}

func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
	s.RegisterService(&Greeter_ServiceDesc, srv)
}

func _Greeter_GetStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(StreamReqData)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(GreeterServer).GetStream(m, &greeterGetStreamServer{stream})
}

type Greeter_GetStreamServer interface {
	Send(*StreamResData) error
	grpc.ServerStream
}

type greeterGetStreamServer struct {
	grpc.ServerStream
}

func (x *greeterGetStreamServer) Send(m *StreamResData) error {
	return x.ServerStream.SendMsg(m)
}

// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "pb.Greeter",
	HandlerType: (*GreeterServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "GetStream",
			Handler:       _Greeter_GetStream_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "pb/hello.proto",
}

服务器端实现

package main

import (
	"fmt"
	"net"
	pb "pro01/pb"
	"time"

	"google.golang.org/grpc"
)

const PORT = ":50051"

type server struct {
	pb.UnimplementedGreeterServer
}

// 服务端 单向流
func (s *server) GetStream(req *pb.StreamReqData, res pb.Greeter_GetStreamServer) error {
	i := 0
	for {
		i++
		res.Send(&pb.StreamResData{Data: fmt.Sprintf("%v", time.Now().Unix())})
		time.Sleep(1 * time.Second)
		if i > 10 {
			break
		}
	}
	return nil
}

func main() {
	//监听
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		return
	}
	fmt.Println("服务器开始推送...")

	//创建一个grpc服务器
	s := grpc.NewServer()

	//注册事件
	pb.RegisterGreeterServer(s, &server{})

	//处理链接
	s.Serve(lis)

}

客户端实现

package main

import (
	"context"
	"log"
	pb "pro01/pb"

	"google.golang.org/grpc"
)

const (
	ADDRESS = "localhost:50051"
)

func main() {
	// 通过grpc库,建立一个连接
	conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
	if err != nil {
		return
	}
	defer conn.Close()

	//通过建立的连接生成一个client对象
	c := pb.NewGreeterClient(conn)

	//调用服务器端推送流
	reqstreamData := &pb.StreamReqData{Data: "Psych"}
	res, _ := c.GetStream(context.Background(), reqstreamData)
	for {
		aa, err := res.Recv()
		if err != nil {
			log.Println(err)
			break
		}
		log.Println(aa)
	}
}

运行结果

go run server/main.go

gRPC服务的定义和服务的种类_第1张图片

go run client/main.go

gRPC服务的定义和服务的种类_第2张图片

grpc stream实例2-客户端单向流

创建protobuf message

syntax = "proto3";

option go_package= "./;pb";

package pb;

service Greeter {
  // 客户端 推送流
  rpc PutStream (stream StreamReqData) returns (StreamResData){}
}

// request
message StreamReqData {
   string data = 1;
}

// response
message StreamResData {
   string data = 1;
}

编译

protoc --go_out=./pb ./pb/hello.proto
protoc --go-grpc_out=./pb ./pb/hello.proto

生成的文件

pb\hello.pb.go:

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.26.0
// 	protoc        v3.21.6
// source: pb/hello.proto

package pb

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

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)
)

// request
type StreamReqData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamReqData) Reset() {
	*x = StreamReqData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamReqData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamReqData) ProtoMessage() {}

func (x *StreamReqData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamReqData.ProtoReflect.Descriptor instead.
func (*StreamReqData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{0}
}

func (x *StreamReqData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

// response
type StreamResData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamResData) Reset() {
	*x = StreamResData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamResData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamResData) ProtoMessage() {}

func (x *StreamResData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamResData.ProtoReflect.Descriptor instead.
func (*StreamResData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{1}
}

func (x *StreamResData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

var File_pb_hello_proto protoreflect.FileDescriptor

var file_pb_hello_proto_rawDesc = []byte{
	0x0a, 0x0e, 0x70, 0x62, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x12, 0x02, 0x70, 0x62, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65,
	0x71, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20,
	0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72,
	0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
	0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x40,
	0x0a, 0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x35, 0x0a, 0x09, 0x50, 0x75, 0x74,
	0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53, 0x74, 0x72, 0x65,
	0x61, 0x6d, 0x52, 0x65, 0x71, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53,
	0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x22, 0x00, 0x28, 0x01,
	0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2f, 0x3b, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x33,
}

var (
	file_pb_hello_proto_rawDescOnce sync.Once
	file_pb_hello_proto_rawDescData = file_pb_hello_proto_rawDesc
)

func file_pb_hello_proto_rawDescGZIP() []byte {
	file_pb_hello_proto_rawDescOnce.Do(func() {
		file_pb_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_hello_proto_rawDescData)
	})
	return file_pb_hello_proto_rawDescData
}

var file_pb_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pb_hello_proto_goTypes = []interface{}{
	(*StreamReqData)(nil), // 0: pb.StreamReqData
	(*StreamResData)(nil), // 1: pb.StreamResData
}
var file_pb_hello_proto_depIdxs = []int32{
	0, // 0: pb.Greeter.PutStream:input_type -> pb.StreamReqData
	1, // 1: pb.Greeter.PutStream:output_type -> pb.StreamResData
	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_pb_hello_proto_init() }
func file_pb_hello_proto_init() {
	if File_pb_hello_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_pb_hello_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamReqData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_pb_hello_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamResData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_pb_hello_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_pb_hello_proto_goTypes,
		DependencyIndexes: file_pb_hello_proto_depIdxs,
		MessageInfos:      file_pb_hello_proto_msgTypes,
	}.Build()
	File_pb_hello_proto = out.File
	file_pb_hello_proto_rawDesc = nil
	file_pb_hello_proto_goTypes = nil
	file_pb_hello_proto_depIdxs = nil
}

pb\hello_grpc.pb.go:

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.

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.32.0 or later.
const _ = grpc.SupportPackageIsVersion7

// GreeterClient is the client API for Greeter 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.
type GreeterClient interface {
	// 客户端 推送流
	PutStream(ctx context.Context, opts ...grpc.CallOption) (Greeter_PutStreamClient, error)
}

type greeterClient struct {
	cc grpc.ClientConnInterface
}

func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
	return &greeterClient{cc}
}

func (c *greeterClient) PutStream(ctx context.Context, opts ...grpc.CallOption) (Greeter_PutStreamClient, error) {
	stream, err := c.cc.NewStream(ctx, &Greeter_ServiceDesc.Streams[0], "/pb.Greeter/PutStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &greeterPutStreamClient{stream}
	return x, nil
}

type Greeter_PutStreamClient interface {
	Send(*StreamReqData) error
	CloseAndRecv() (*StreamResData, error)
	grpc.ClientStream
}

type greeterPutStreamClient struct {
	grpc.ClientStream
}

func (x *greeterPutStreamClient) Send(m *StreamReqData) error {
	return x.ClientStream.SendMsg(m)
}

func (x *greeterPutStreamClient) CloseAndRecv() (*StreamResData, error) {
	if err := x.ClientStream.CloseSend(); err != nil {
		return nil, err
	}
	m := new(StreamResData)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
	// 客户端 推送流
	PutStream(Greeter_PutStreamServer) error
	mustEmbedUnimplementedGreeterServer()
}

// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}

func (UnimplementedGreeterServer) PutStream(Greeter_PutStreamServer) error {
	return status.Errorf(codes.Unimplemented, "method PutStream not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}

// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
	mustEmbedUnimplementedGreeterServer()
}

func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
	s.RegisterService(&Greeter_ServiceDesc, srv)
}

func _Greeter_PutStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(GreeterServer).PutStream(&greeterPutStreamServer{stream})
}

type Greeter_PutStreamServer interface {
	SendAndClose(*StreamResData) error
	Recv() (*StreamReqData, error)
	grpc.ServerStream
}

type greeterPutStreamServer struct {
	grpc.ServerStream
}

func (x *greeterPutStreamServer) SendAndClose(m *StreamResData) error {
	return x.ServerStream.SendMsg(m)
}

func (x *greeterPutStreamServer) Recv() (*StreamReqData, error) {
	m := new(StreamReqData)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "pb.Greeter",
	HandlerType: (*GreeterServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "PutStream",
			Handler:       _Greeter_PutStream_Handler,
			ClientStreams: true,
		},
	},
	Metadata: "pb/hello.proto",
}

服务器端实现

package main

import (
	"log"
	"net"
	pb "pro01/pb"

	"google.golang.org/grpc"
)

const PORT = ":50051"

type server struct {
	pb.UnimplementedGreeterServer
}

// 客户端 单向流
func (s *server) PutStream(cliStr pb.Greeter_PutStreamServer) error {
	for {
		if tem, err := cliStr.Recv(); err == nil {
			log.Println(tem)
		} else {
			log.Println("break, err :", err)
			break
		}

	}
	return nil
}

func main() {
	//监听
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		return
	}

	//创建一个grpc服务器
	s := grpc.NewServer()

	//注册事件
	pb.RegisterGreeterServer(s, &server{})

	//处理链接
	s.Serve(lis)

}

客户端实现

package main

import (
	"context"
	pb "pro01/pb"
	"time"

	"google.golang.org/grpc"
)

const (
	ADDRESS = "localhost:50051"
)

func main() {
	// 通过grpc库,建立一个连接
	conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
	if err != nil {
		return
	}
	defer conn.Close()

	//通过建立的连接生成一个client对象
	c := pb.NewGreeterClient(conn)

	//客户端推送流
	putRes, _ := c.PutStream(context.Background())
	i := 1
	for {
		i++
		putRes.Send(&pb.StreamReqData{Data: "Psych"})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}
}

运行结果

go run server/main.go

gRPC服务的定义和服务的种类_第3张图片

go run client/main.go

在这里插入图片描述

grpc stream实例3-双向流

创建protobuf message

syntax = "proto3";

option go_package= "./;pb";

package pb;

service Greeter {
  // 双向流
  rpc AllStream (stream StreamReqData) returns (stream StreamResData){}
}

// request
message StreamReqData {
   string data = 1;
}

// response
message StreamResData {
   string data = 1;
}

编译

protoc --go_out=./pb ./pb/hello.proto
protoc --go-grpc_out=./pb ./pb/hello.proto

生成的文件

pb\hello.pb.go:

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.26.0
// 	protoc        v3.21.6
// source: pb/hello.proto

package pb

import (
	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
	reflect "reflect"
	sync "sync"
)

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)
)

// request
type StreamReqData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamReqData) Reset() {
	*x = StreamReqData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[0]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamReqData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamReqData) ProtoMessage() {}

func (x *StreamReqData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[0]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamReqData.ProtoReflect.Descriptor instead.
func (*StreamReqData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{0}
}

func (x *StreamReqData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

// response
type StreamResData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

	Data string `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (x *StreamResData) Reset() {
	*x = StreamResData{}
	if protoimpl.UnsafeEnabled {
		mi := &file_pb_hello_proto_msgTypes[1]
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		ms.StoreMessageInfo(mi)
	}
}

func (x *StreamResData) String() string {
	return protoimpl.X.MessageStringOf(x)
}

func (*StreamResData) ProtoMessage() {}

func (x *StreamResData) ProtoReflect() protoreflect.Message {
	mi := &file_pb_hello_proto_msgTypes[1]
	if protoimpl.UnsafeEnabled && x != nil {
		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
		if ms.LoadMessageInfo() == nil {
			ms.StoreMessageInfo(mi)
		}
		return ms
	}
	return mi.MessageOf(x)
}

// Deprecated: Use StreamResData.ProtoReflect.Descriptor instead.
func (*StreamResData) Descriptor() ([]byte, []int) {
	return file_pb_hello_proto_rawDescGZIP(), []int{1}
}

func (x *StreamResData) GetData() string {
	if x != nil {
		return x.Data
	}
	return ""
}

var File_pb_hello_proto protoreflect.FileDescriptor

var file_pb_hello_proto_rawDesc = []byte{
	0x0a, 0x0e, 0x70, 0x62, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f,
	0x12, 0x02, 0x70, 0x62, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65,
	0x71, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61, 0x74, 0x61, 0x18, 0x01, 0x20,
	0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x22, 0x23, 0x0a, 0x0d, 0x53, 0x74, 0x72,
	0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x12, 0x12, 0x0a, 0x04, 0x64, 0x61,
	0x74, 0x61, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x64, 0x61, 0x74, 0x61, 0x32, 0x42,
	0x0a, 0x07, 0x47, 0x72, 0x65, 0x65, 0x74, 0x65, 0x72, 0x12, 0x37, 0x0a, 0x09, 0x41, 0x6c, 0x6c,
	0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53, 0x74, 0x72, 0x65,
	0x61, 0x6d, 0x52, 0x65, 0x71, 0x44, 0x61, 0x74, 0x61, 0x1a, 0x11, 0x2e, 0x70, 0x62, 0x2e, 0x53,
	0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x44, 0x61, 0x74, 0x61, 0x22, 0x00, 0x28, 0x01,
	0x30, 0x01, 0x42, 0x07, 0x5a, 0x05, 0x2e, 0x2f, 0x3b, 0x70, 0x62, 0x62, 0x06, 0x70, 0x72, 0x6f,
	0x74, 0x6f, 0x33,
}

var (
	file_pb_hello_proto_rawDescOnce sync.Once
	file_pb_hello_proto_rawDescData = file_pb_hello_proto_rawDesc
)

func file_pb_hello_proto_rawDescGZIP() []byte {
	file_pb_hello_proto_rawDescOnce.Do(func() {
		file_pb_hello_proto_rawDescData = protoimpl.X.CompressGZIP(file_pb_hello_proto_rawDescData)
	})
	return file_pb_hello_proto_rawDescData
}

var file_pb_hello_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_pb_hello_proto_goTypes = []interface{}{
	(*StreamReqData)(nil), // 0: pb.StreamReqData
	(*StreamResData)(nil), // 1: pb.StreamResData
}
var file_pb_hello_proto_depIdxs = []int32{
	0, // 0: pb.Greeter.AllStream:input_type -> pb.StreamReqData
	1, // 1: pb.Greeter.AllStream:output_type -> pb.StreamResData
	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_pb_hello_proto_init() }
func file_pb_hello_proto_init() {
	if File_pb_hello_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_pb_hello_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamReqData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_pb_hello_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamResData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
	}
	type x struct{}
	out := protoimpl.TypeBuilder{
		File: protoimpl.DescBuilder{
			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
			RawDescriptor: file_pb_hello_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_pb_hello_proto_goTypes,
		DependencyIndexes: file_pb_hello_proto_depIdxs,
		MessageInfos:      file_pb_hello_proto_msgTypes,
	}.Build()
	File_pb_hello_proto = out.File
	file_pb_hello_proto_rawDesc = nil
	file_pb_hello_proto_goTypes = nil
	file_pb_hello_proto_depIdxs = nil
}

pb\hello_grpc.pb.go:

// Code generated by protoc-gen-go-grpc. DO NOT EDIT.

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.32.0 or later.
const _ = grpc.SupportPackageIsVersion7

// GreeterClient is the client API for Greeter 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.
type GreeterClient interface {
	// 双向流
	AllStream(ctx context.Context, opts ...grpc.CallOption) (Greeter_AllStreamClient, error)
}

type greeterClient struct {
	cc grpc.ClientConnInterface
}

func NewGreeterClient(cc grpc.ClientConnInterface) GreeterClient {
	return &greeterClient{cc}
}

func (c *greeterClient) AllStream(ctx context.Context, opts ...grpc.CallOption) (Greeter_AllStreamClient, error) {
	stream, err := c.cc.NewStream(ctx, &Greeter_ServiceDesc.Streams[0], "/pb.Greeter/AllStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &greeterAllStreamClient{stream}
	return x, nil
}

type Greeter_AllStreamClient interface {
	Send(*StreamReqData) error
	Recv() (*StreamResData, error)
	grpc.ClientStream
}

type greeterAllStreamClient struct {
	grpc.ClientStream
}

func (x *greeterAllStreamClient) Send(m *StreamReqData) error {
	return x.ClientStream.SendMsg(m)
}

func (x *greeterAllStreamClient) Recv() (*StreamResData, error) {
	m := new(StreamResData)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// GreeterServer is the server API for Greeter service.
// All implementations must embed UnimplementedGreeterServer
// for forward compatibility
type GreeterServer interface {
	// 双向流
	AllStream(Greeter_AllStreamServer) error
	mustEmbedUnimplementedGreeterServer()
}

// UnimplementedGreeterServer must be embedded to have forward compatible implementations.
type UnimplementedGreeterServer struct {
}

func (UnimplementedGreeterServer) AllStream(Greeter_AllStreamServer) error {
	return status.Errorf(codes.Unimplemented, "method AllStream not implemented")
}
func (UnimplementedGreeterServer) mustEmbedUnimplementedGreeterServer() {}

// UnsafeGreeterServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to GreeterServer will
// result in compilation errors.
type UnsafeGreeterServer interface {
	mustEmbedUnimplementedGreeterServer()
}

func RegisterGreeterServer(s grpc.ServiceRegistrar, srv GreeterServer) {
	s.RegisterService(&Greeter_ServiceDesc, srv)
}

func _Greeter_AllStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(GreeterServer).AllStream(&greeterAllStreamServer{stream})
}

type Greeter_AllStreamServer interface {
	Send(*StreamResData) error
	Recv() (*StreamReqData, error)
	grpc.ServerStream
}

type greeterAllStreamServer struct {
	grpc.ServerStream
}

func (x *greeterAllStreamServer) Send(m *StreamResData) error {
	return x.ServerStream.SendMsg(m)
}

func (x *greeterAllStreamServer) Recv() (*StreamReqData, error) {
	m := new(StreamReqData)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Greeter_ServiceDesc is the grpc.ServiceDesc for Greeter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Greeter_ServiceDesc = grpc.ServiceDesc{
	ServiceName: "pb.Greeter",
	HandlerType: (*GreeterServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "AllStream",
			Handler:       _Greeter_AllStream_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
	Metadata: "pb/hello.proto",
}

服务器端实现

package main

import (
	"fmt"
	"log"
	"net"
	pb "pro01/pb"
	"sync"
	"time"

	"google.golang.org/grpc"
)

const PORT = ":50051"

type server struct {
	pb.UnimplementedGreeterServer
}

// 服务器端客户端 双向流
func (s *server) AllStream(allStr pb.Greeter_AllStreamServer) error {
	wg := sync.WaitGroup{}
	wg.Add(2)

	// 接收数据
	go func() {
		for {
			data, _ := allStr.Recv()
			log.Println(data)
		}
	}()

	// 发送数据
	go func() {
		for {
			allStr.Send(&pb.StreamResData{Data: "from server"})
			time.Sleep(time.Second)
		}
	}()

	wg.Wait()

	return nil
}

func main() {
	//监听
	lis, err := net.Listen("tcp", PORT)
	if err != nil {
		return
	}

	//创建一个grpc服务器
	s := grpc.NewServer()
	fmt.Println("服务器开始推送...")

	//注册事件
	pb.RegisterGreeterServer(s, &server{})

	//处理链接
	s.Serve(lis)

}

客户端实现

package main

import (
	"context"
	"log"
	pb "pro01/pb"
	"time"

	"google.golang.org/grpc"
)

const (
	ADDRESS = "localhost:50051"
)

func main() {
	// 通过grpc库,建立一个连接
	conn, err := grpc.Dial(ADDRESS, grpc.WithInsecure())
	if err != nil {
		return
	}
	defer conn.Close()

	//通过建立的连接生成一个client对象
	c := pb.NewGreeterClient(conn)

	//客户端服务器端 双向流
	allStr, _ := c.AllStream(context.Background())

	// 接收数据
	go func() {
		for {
			data, _ := allStr.Recv()
			log.Println(data)
		}
	}()

	//发送数据
	go func() {
		for {
			allStr.Send(&pb.StreamReqData{Data: "from client"})
			time.Sleep(time.Second)
		}
	}()

	select {}
}

运行结果

go run server/main.go

gRPC服务的定义和服务的种类_第4张图片

go run client/main.go

gRPC服务的定义和服务的种类_第5张图片

你可能感兴趣的:(gRPC,学习,golang,rpc)