How to implement asynchronous rpc in grpc?

92 views
Skip to first unread message

qplc

unread,
Nov 12, 2018, 7:07:56 AM11/12/18
to grpc.io
Hi,

I've implemented below service definition in my grpc server/client application.

service TestService {
  rpc testRPCCall(stream Test) returns (stream Test) {}
}

I found below stubs can be implemented on proto file compilation.
TestServiceGrpc.TestServiceStub
TestServiceGrpc.TestServiceBlockingStub
TestServiceGrpc.TestServiceFutureStub
TestServiceGrpc.TestServiceImplBase

I want to adapt asynchronous behavior of rpc calls. But, I'm not sure which one of above should be implemented. Is it mandatory to stream a rpc call(stream Test) as mentioned in above service definition for asynchronous implementation?


Thanks in advance.

Carl Mastrangelo

unread,
Nov 14, 2018, 11:53:24 AM11/14/18
to grpc.io
TestServiceStub is the main asynchronous stub, and is built around the idea of the Observable / Observer pattern.  RxJava uses this pattern, for instance.   

One thing to note, if you don't like those stubs, you can call the ClientCall and ClientCall.Listener directly.   You can't use the generated stub library, but it does have async behavior.   (Personally, I use it, but copy-paste the MethodDescriptors from the generated code.) 

qplc

unread,
Nov 14, 2018, 12:41:45 PM11/14/18
to grpc.io
Thank you Carl for your response.

What if I don't use prefix 'stream' in service definition, shall rpc calls still be executed in asynchronous manner by implementing TestServiceGrpc.TestServiceStub?

Modified service def:
service TestService {
  rpc testRPCCall(Test) returns (Test) {}
}

Carl Mastrangelo

unread,
Nov 14, 2018, 2:28:56 PM11/14/18
to grpc.io
Yes.  It is still async.  

Do be aware that flow control works slightly differently for RPCs that don't have "stream" on them (we call these "unary" RPCs).   This is not usually an issue unless you are sending very fast or lots of data (like sustained Gigabits  per second).  

constan...@gmail.com

unread,
Nov 14, 2018, 4:57:20 PM11/14/18
to grpc.io
Why not using FutureStub? Seems it returning a ListenableFuture already for client to use it? 


在 2018年11月14日星期三 UTC-5下午2:28:56,Carl Mastrangelo写道:

Carl Mastrangelo

unread,
Nov 15, 2018, 2:01:06 PM11/15/18
to grpc.io
Future stub is only suitable for Unary RPCs.   If you look at how the stub library is implemented, BlockingStubs wrap the FutureStubs, which wrap the regular Stubs, which themselves wrap ClientCall and ServerCall.  All are layers on top of the other, and get more advanced the farther down the layers you go.  The higher up, the more simple it is to use.

xi...@compass.com

unread,
Nov 16, 2018, 9:14:23 AM11/16/18
to grpc.io
I see. thanks

qplc

unread,
Nov 19, 2018, 11:18:02 PM11/19/18
to grpc.io
Thanks Carl. I'm trying to use async calls without streaming.


On Monday, November 12, 2018 at 5:37:56 PM UTC+5:30, qplc wrote:
Reply all
Reply to author
Forward
0 new messages