gRPC服务端数据流快速体验

本文介绍了gRPC中的服务端数据流模式,展示了如何使用Proto3定义服务和消息类型,以及客户端和服务器的实现。客户端发送股票代码,服务端持续返回实时股票数据。示例代码包括Proto定义、Go代码生成以及服务器和客户端的实现,展示了服务端如何不断推送数据到客户端直到特定条件满足。
摘要由CSDN通过智能技术生成

简介

服务端数据流模式(Server-side streaming RPC)是客户端发起一次请求,服务端返回一段连续的数据流。典型的应用场景是客户端向服务端发送一个股票代码,服务端就把该股票的实时数据源源不断的返回给客户端。

代码

proto

syntax = "proto3";
option go_package = ".;proto";

service GetStream{
    rpc GetStream(StreamRequestData) returns (stream StreamResponseData);
}

message StreamRequestData{
  string data = 1;
}

message StreamResponseData{
  string data = 1;
}

.pb.go

// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// 	protoc-gen-go v1.28.0
// 	protoc        v3.19.4
// source: getstream.proto

package proto

import (
	context "context"
	grpc "google.golang.org/grpc"
	codes "google.golang.org/grpc/codes"
	status "google.golang.org/grpc/status"
	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)
)

type StreamRequestData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

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

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

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

func (*StreamRequestData) ProtoMessage() {}

func (x *StreamRequestData) ProtoReflect() protoreflect.Message {
	mi := &file_getstream_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 StreamRequestData.ProtoReflect.Descriptor instead.
func (*StreamRequestData) Descriptor() ([]byte, []int) {
	return file_getstream_proto_rawDescGZIP(), []int{0}
}

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

type StreamResponseData struct {
	state         protoimpl.MessageState
	sizeCache     protoimpl.SizeCache
	unknownFields protoimpl.UnknownFields

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

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

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

func (*StreamResponseData) ProtoMessage() {}

func (x *StreamResponseData) ProtoReflect() protoreflect.Message {
	mi := &file_getstream_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 StreamResponseData.ProtoReflect.Descriptor instead.
func (*StreamResponseData) Descriptor() ([]byte, []int) {
	return file_getstream_proto_rawDescGZIP(), []int{1}
}

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

var File_getstream_proto protoreflect.FileDescriptor

var file_getstream_proto_rawDesc = []byte{
	0x0a, 0x0f, 0x67, 0x65, 0x74, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x2e, 0x70, 0x72, 0x6f, 0x74,
	0x6f, 0x22, 0x27, 0x0a, 0x11, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65,
	0x73, 0x74, 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, 0x28, 0x0a, 0x12, 0x53, 0x74,
	0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 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, 0x43, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61,
	0x6d, 0x12, 0x36, 0x0a, 0x09, 0x47, 0x65, 0x74, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x12, 0x12,
	0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x44, 0x61,
	0x74, 0x61, 0x1a, 0x13, 0x2e, 0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x52, 0x65, 0x73, 0x70, 0x6f,
	0x6e, 0x73, 0x65, 0x44, 0x61, 0x74, 0x61, 0x30, 0x01, 0x42, 0x09, 0x5a, 0x07, 0x2e, 0x3b, 0x70,
	0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
}

var (
	file_getstream_proto_rawDescOnce sync.Once
	file_getstream_proto_rawDescData = file_getstream_proto_rawDesc
)

func file_getstream_proto_rawDescGZIP() []byte {
	file_getstream_proto_rawDescOnce.Do(func() {
		file_getstream_proto_rawDescData = protoimpl.X.CompressGZIP(file_getstream_proto_rawDescData)
	})
	return file_getstream_proto_rawDescData
}

var file_getstream_proto_msgTypes = make([]protoimpl.MessageInfo, 2)
var file_getstream_proto_goTypes = []interface{}{
	(*StreamRequestData)(nil),  // 0: StreamRequestData
	(*StreamResponseData)(nil), // 1: StreamResponseData
}
var file_getstream_proto_depIdxs = []int32{
	0, // 0: GetStream.GetStream:input_type -> StreamRequestData
	1, // 1: GetStream.GetStream:output_type -> StreamResponseData
	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_getstream_proto_init() }
func file_getstream_proto_init() {
	if File_getstream_proto != nil {
		return
	}
	if !protoimpl.UnsafeEnabled {
		file_getstream_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamRequestData); i {
			case 0:
				return &v.state
			case 1:
				return &v.sizeCache
			case 2:
				return &v.unknownFields
			default:
				return nil
			}
		}
		file_getstream_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
			switch v := v.(*StreamResponseData); 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_getstream_proto_rawDesc,
			NumEnums:      0,
			NumMessages:   2,
			NumExtensions: 0,
			NumServices:   1,
		},
		GoTypes:           file_getstream_proto_goTypes,
		DependencyIndexes: file_getstream_proto_depIdxs,
		MessageInfos:      file_getstream_proto_msgTypes,
	}.Build()
	File_getstream_proto = out.File
	file_getstream_proto_rawDesc = nil
	file_getstream_proto_goTypes = nil
	file_getstream_proto_depIdxs = nil
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6

// GetStreamClient is the client API for GetStream service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type GetStreamClient interface {
	GetStream(ctx context.Context, in *StreamRequestData, opts ...grpc.CallOption) (GetStream_GetStreamClient, error)
}

type getStreamClient struct {
	cc grpc.ClientConnInterface
}

func NewGetStreamClient(cc grpc.ClientConnInterface) GetStreamClient {
	return &getStreamClient{cc}
}

func (c *getStreamClient) GetStream(ctx context.Context, in *StreamRequestData, opts ...grpc.CallOption) (GetStream_GetStreamClient, error) {
	stream, err := c.cc.NewStream(ctx, &_GetStream_serviceDesc.Streams[0], "/GetStream/GetStream", opts...)
	if err != nil {
		return nil, err
	}
	x := &getStreamGetStreamClient{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 GetStream_GetStreamClient interface {
	Recv() (*StreamResponseData, error)
	grpc.ClientStream
}

type getStreamGetStreamClient struct {
	grpc.ClientStream
}

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

// GetStreamServer is the server API for GetStream service.
type GetStreamServer interface {
	GetStream(*StreamRequestData, GetStream_GetStreamServer) error
}

// UnimplementedGetStreamServer can be embedded to have forward compatible implementations.
type UnimplementedGetStreamServer struct {
}

func (*UnimplementedGetStreamServer) GetStream(*StreamRequestData, GetStream_GetStreamServer) error {
	return status.Errorf(codes.Unimplemented, "method GetStream not implemented")
}

func RegisterGetStreamServer(s *grpc.Server, srv GetStreamServer) {
	s.RegisterService(&_GetStream_serviceDesc, srv)
}

func _GetStream_GetStream_Handler(srv interface{}, stream grpc.ServerStream) error {
	m := new(StreamRequestData)
	if err := stream.RecvMsg(m); err != nil {
		return err
	}
	return srv.(GetStreamServer).GetStream(m, &getStreamGetStreamServer{stream})
}

type GetStream_GetStreamServer interface {
	Send(*StreamResponseData) error
	grpc.ServerStream
}

type getStreamGetStreamServer struct {
	grpc.ServerStream
}

func (x *getStreamGetStreamServer) Send(m *StreamResponseData) error {
	return x.ServerStream.SendMsg(m)
}

var _GetStream_serviceDesc = grpc.ServiceDesc{
	ServiceName: "GetStream",
	HandlerType: (*GetStreamServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "GetStream",
			Handler:       _GetStream_GetStream_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "getstream.proto",
}

Server

package main

import (
	"ShopBefore/rpc/grpc_get_stream/proto"
	"fmt"
	"google.golang.org/grpc"
	"net"
	"time"
)

type Server struct {}

// GetStream 服务端数据流模式
func (s Server) GetStream(data *proto.StreamRequestData, server proto.GetStream_GetStreamServer) error {
	i := 0
	for{
		i++
		err := server.Send(&proto.StreamResponseData{Data: fmt.Sprintf("服务端发送信息%d", i)})
		if err != nil {
			return err
		}
		time.Sleep(time.Second)
		if i > 10 {
			// 发送10条消息就停止发送
			break
		}
	}
	return nil
}

func main() {
	// 监听端口8081
	listen, _ := net.Listen("tcp", ":8081")
	// 创建一个gRPC服务器
	server := grpc.NewServer()
	// 注册事件
	proto.RegisterGetStreamServer(server,&Server{})
	_ = server.Serve(listen)
}

Client

package main

import (
	"ShopBefore/rpc/grpc_get_stream/proto"
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

func main() {
	// 通过grpc库建立一个连接
	conn, _ := grpc.Dial("localhost:8081", grpc.WithTransportCredentials(insecure.NewCredentials()))
	defer func(conn *grpc.ClientConn) {
		_ = conn.Close()
	}(conn)
	// 通过刚刚建立的连接生成一个client对象
	client := proto.NewGetStreamClient(conn)
	// 调用服务端推送流
	resp, _ := client.GetStream(context.Background(), &proto.StreamRequestData{Data: "a"})
	for  {
		recv, err := resp.Recv()
		if err != nil {
			log.Println(err)
			break
		}
		log.Println(recv.Data)
	}
}

// 2022/05/12 20:43:29 服务端发送信息1
// 2022/05/12 20:43:30 服务端发送信息2
// 2022/05/12 20:43:31 服务端发送信息3
// 2022/05/12 20:43:32 服务端发送信息4
// 2022/05/12 20:43:33 服务端发送信息5
// 2022/05/12 20:43:34 服务端发送信息6
// 2022/05/12 20:43:35 服务端发送信息7
// 2022/05/12 20:43:36 服务端发送信息8
// 2022/05/12 20:43:37 服务端发送信息9
// 2022/05/12 20:43:38 服务端发送信息10
// 2022/05/12 20:43:39 服务端发送信息11
// 2022/05/12 20:43:40 EOF

只是想理解一下grpc中的服务端数据流调用,对代码中的部分error都没有进行处理.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.番茄炒蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值