HelloWorldServer TLS示例
使用API:
server = Grpc.newServerBuilderForPort(port, tlscredentials)
.addService(new GreeterImpl())
.build();
然而,这个API不允许指定超时。基于Netty的API允许这种超时。例如:
server = NettyServerBuilder.forPort(port)
.channelType(NioServerSocketChannel.class)
.permitKeepAliveTime(timeout) // can specify keepalive parameters
.permitKeepAliveWithoutCalls(true) // can specify keepalive parameters
.addService(new GreeterImpl())
.sslContext(getSslContextBuilder().build())
.build();
示例代码看起来更干净,但我找不到一种简单的方法来指定keepalive参数。什么好主意吗?
因为Grpc.newServerBuilderForPort()
返回类型声明为ServerBuilder
,而您想要的方法在NettyServerBuilder
中可用。您可以获取构建器并检查其类型,如下所示:
ServerBuilder<?> builder = Grpc.newServerBuilderForPort(port, tlscredentials);
if (builder instanceof NettyServerBuilder) {
NettyServerBuilder nsBuilder = (NettyServerBuilder)builder;
builder = nsBuilder
.channelType(NioServerSocketChannel.class)
.permitKeepAliveTime(timeout) // can specify keepalive parameters
.permitKeepAliveWithoutCalls(true); // can specify keepalive parameters
}
server = builder.addService(new GreeterImpl()).build();
您不需要设置sslContext,因为您已经使用了tlsCredentials
。