我试图阻止GRPC在每个通道上使用多个线程。为此,我使用以下代码设置了一个单线程执行器:
for (int i = 0; i < 3 * numFaults + 1; i++) {
//One thread for each channel
ManagedChannel channel = NettyChannelBuilder
.forAddress(host, port + i + 1)
.usePlaintext()
.executor(Executors.newSingleThreadExecutor())
.build();然后,我为每个通道创建一个asyn存根。
然而,这似乎不起作用,因为我仍然在我的程序中产生太多的线程,最终耗尽内存。
我是否应该将executor传递给存根?还是有什么根本性的问题。
提前感谢
发布于 2020-04-20 09:39:21
额外产生的线程可能是 EventLoop 线程(默认情况下它最多可以创建 # 个核心线程)。 在 NettyChannelBuilder 中有一个提供 EventLoopGroup 的选项。 要使用此 API,您还需要设置 ChannelType。 EventLoopGroup 和 Channel Type 来自 netty,如果您有兴趣,请参阅链接的 javadoc 了解更多详细信息。
如果是在linux上,则可以使用Epoll,否则使用NIO是当前的gRPC行为。下面的示例是使用NIO。所有网络事件都发生在事件循环线程上,因此使用较少的线程会显著影响整体性能(取决于通道的使用方式)。您还可以考虑使用directExecutor并为EventLoopGroup分配更多的线程。
NioEventLoopGroup sharedEventLoopGroup = new NioEventLoopGroup(numThread);
ManagedChannel channel = NettyChannelBuilder
.forAddress(host, port + i + 1)
.usePlaintext()
.channelType(NioSocketChannel.class)
.eventLoopGroup(sharedEventLoopGroup)
.executor(Executors.newSingleThreadExecutor())
.build();https://stackoverflow.com/questions/61305866
复制相似问题