[Java] Sharing ManagedChannels and Stubs - best practices?

1,473 views
Skip to first unread message

Ryan Michela

unread,
Sep 11, 2017, 4:46:08 PM9/11/17
to grpc.io
What are the best practices for managing the lifecycle of ManagedChannel and client stub instances? 

DI frameworks tend to favor long-lived singleton objects. What is the best practice for building gRPC clients with DI?
  1. Inject a long-lived stub wrapping a long-lived ManagedChannel
  2. Locally instantiate a short-lived stub wrapping an injected long-lived ManagedChannel
  3. Create a fresh stub and ManagedChannel for each "unit of work" (multiple successive calls)
  4. Create a fresh stub and ManagedChannel for each request

Rama Rao

unread,
Sep 12, 2017, 6:18:09 AM9/12/17
to Ryan Michela, grpc.io

--
You received this message because you are subscribed to the Google Groups "grpc.io" group.
To unsubscribe from this group and stop receiving emails from it, send an email to grpc-io+unsubscribe@googlegroups.com.
To post to this group, send email to grp...@googlegroups.com.
Visit this group at https://groups.google.com/group/grpc-io.
To view this discussion on the web visit https://groups.google.com/d/msgid/grpc-io/9f92811a-d913-4931-af95-c26a1c807513%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Spencer Fang

unread,
Sep 13, 2017, 10:35:33 AM9/13/17
to Rama Rao, Ryan Michela, grpc.io
In general, a ManagedChannel should be long lived because creating it is relatively expensive, but creating stubs for RPCs on the channel is cheap. I would suggest keeping a long lived shared ManagedChannel around, and creating a fresh stub for each RPC. ManagedChannel is thread safe and is designed to be shared in this way. This would be #2 in your list.


For more options, visit https://groups.google.com/d/optout.



--
Spencer Fang
Reply all
Reply to author
Forward
0 new messages