可以使用gRPC推送数据吗? [英] Is it OK to use gRPC to push data?

查看:684
本文介绍了可以使用gRPC推送数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将数据从gRPC服务器推送到客户端是否是一个好主意.基本上我想在gRPC中使用发布/订阅模式. 我的方法是在服务器实现上返回一个我从未关闭过的响应流.然后,客户端将拥有一个永无止境的go例程来负责读取此流.

I'm wondering if it's a good idea to push data from gRPC server to a client. Basically I want to use a pub/sub pattern with gRPC. The way I do is that I return a response stream on the server implementation that I never close. Then, the client has a never ending go routine in charge of reading this stream.

这里是一个例子:

service Service {
    rpc RegularChanges (Void) returns (stream Change) {}
}

在服务器端:

func (self *MyServiceImpl) RegularChanges(in *pb.Void, stream pb.Service_RegularChangesServer) error {

    for {
        d, err := time.ParseDuration("1s")
        if err != nil {
            log.Fatalf("Cannot parse duration")
            break;
        }
        time.Sleep(d)
        stream.Send(&pb.Change{Name:"toto", Description:"status changed"})
    }
    return nil
}

在客户端上:

for {
        change, err := streamChanges.Recv()
        if err != nil {
            log.Fatalf("Error retrieving change")
        } else {
            log.Println(change)
        }
}

我只是从go和gRPC开始,但是我知道它基于HTTP2,因此它应该支持推送数据.但是,我不确定这是应该使用gRPC的方式.

I just began with go and gRPC but I know it's based on HTTP2, hence it should support pushing datas. However, I'm not sure this is the way gRPC should be used.

推荐答案

gRPC旨在以这种方式使用.

gRPC is intended to be used in this way.

您仍应考虑客户端在发生故障时应如何表现以及如何在后端之间重新平衡.如果您的连接是通过Internet进行的,则可能还需要通过向客户端和服务器提供KeepaliveParams来启用keepalive来检测连接中断.

You should still consider how the client should behave on failures and how you may want to re-balance across backends. If your connection is going across the Internet, you may also want to enable keepalive to detect connection breakages by providing KeepaliveParams to the client and server.

这篇关于可以使用gRPC推送数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆