可以使用gRPC来推送数据吗?

huangapple go评论63阅读模式
英文:

Is it OK to use gRPC to push data?

问题

我想知道从 gRPC 服务器向客户端推送数据是否是一个好主意。基本上,我想在 gRPC 中使用发布/订阅模式。
我的做法是在服务器实现中返回一个永不关闭的响应流。然后,客户端有一个永不结束的 Go 协程负责读取这个流。

以下是一个示例:

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'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.

Here is an example:

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

On the server side:

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
}

On client:

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

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.

答案1

得分: 9

gRPC旨在以这种方式使用。

您仍然应考虑客户端在失败时的行为以及如何在后端之间重新平衡。如果您的连接跨越互联网,您可能还希望通过向客户端和服务器提供KeepaliveParams来启用保持活动以检测连接中断。

英文:

gRPC is intended to be used in this way.

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.

huangapple
  • 本文由 发表于 2017年4月26日 05:51:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/43621586.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定