繁体   English   中英

如何通过本地套接字而不是在 Scala/java 中的 inet 创建 GRPC 服务

[英]How to create a GRPC service over a local socket rather then inet in scala/java

我的GRPC服务只能被本地机器上的应用程序访问。

我认为如果客户端通过 Unix 域套接字而不是 localhost:port 连接,它的执行速度会更快

我很想了解在这种情况下如何创建 grpc 服务,它应该能够在 CentOS 和 Mac 上运行

目前正在创建这样的服务器:

val server: Server = ServerBuilder.forPort(port).addService(GreeterGrpc.bindService(new GrpcServer, ec)).build().start()

我也尝试过这样的配置:

val server: Server = io.grpc.netty.NettyServerBuilder.forPort(port).addService(ProtoReflectionService.newInstance()).addService(GreeterGrpc.bindService(new GrpcServer, ec)).build().start()

但无法弄清楚如何绑定到本地套接字而不是本地主机

localhost:port应该基本上与Unix域套接字(UDS)一样快。 UDS的主要用例是更好地控制权限和安全性,因为适用Unix文件权限。

Java不支持UDS。 因此,要使用UDS获取grpc-java,您必须使用JNI组件,例如netty-transport-epoll或netty-transport-kqueue。

grpc-java不提供对UDS的开箱即用支持,但是您可以自己将各个部分组合在一起:

// You are responsible for shutting down 'elg' and 'boss'. You
// may want to provide a ThreadFactory to use daemon threads.
EventLoopGroup elg = new EpollEventLoopGroup();

ManagedChannel chan = NettyChannelBuilder
    .forAddress(new DomainSocketAddress("filename"))
    .eventLoopGroup(elg)
    .channelType(EpollDomainSocketChannel.class)
    .build();

EventLoopGroup boss = new EpollEventLoopGroup(1);
Server serv = NettyServerBuilder
    .forAddress(new DomainSocketAddress("filename"))
    .bossEventLoopGroup(boss)
    .workerEventLoopGroup(elg)
    .channelType(EpollServerDomainSocketChannel.class)
    .build();

“老板”事件循环组的唯一工作是accept()新连接。 如果新连接的速率较低,则可以将elg用作bossEventLoopGroup()

您应该在ChannelServer之间尽可能多地共享elg

Epoll在OS X上不可用,因此您需要改用kqueue。 对于kqueue,请使用KQueueEventLoopKQueueDomainSocketChannelKQueueServerDomainSocketChannel而不是它们的epoll副本。

对于未来的读者:Java 16 添加了对 UDS 的支持。 跟踪 Java 16 相关更改的 Netty 问题是https://github.com/netty/netty/issues/10991

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM