下面列出了怎么用io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void tcnative() throws Exception {
server = NettyServerBuilder.forPort(0)
.useTransportSecurity(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
.addService(new SimpleServiceImpl())
.build().start();
channel = NettyChannelBuilder
.forAddress("localhost", server.getPort())
.sslContext(
GrpcSslContexts.configure(SslContextBuilder.forClient(), SslProvider.OPENSSL)
.trustManager(TestUtils.loadCert("ca.pem")).build())
.overrideAuthority("foo.test.google.fr")
.build();
SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel);
assertThat(SimpleResponse.getDefaultInstance())
.isEqualTo(stub.unaryRpc(SimpleRequest.getDefaultInstance()));
}
@Bean
public GrpcServerConfigurer grpcServerConfigurer(GrpcProperties grpcProperties) {
NettyProperties nettyProperties = grpcProperties.getNetty();
Executor executor = new ThreadPoolExecutor(
nettyProperties.getExecutorCoreThreadCount(),
nettyProperties.getExecutorMaxThreadCount(),
nettyProperties.getThreadKeepAliveTime(),
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("grpc-executor-%d")
.build());
return serverBuilder -> ((NettyServerBuilder) serverBuilder)
.executor(executor)
.flowControlWindow(nettyProperties.getFlowControlWindow())
.maxConcurrentCallsPerConnection(nettyProperties.getMaxConcurrentCallsPerConnection())
.maxInboundMessageSize(nettyProperties.getMaxInboundMessageSize())
.maxInboundMetadataSize(nettyProperties.getMaxInboundMetadataSize());
}
@Before
public void setUp() throws Exception {
this.sampleService = new SampleServiceImpl();
this.server = NettyServerBuilder.forPort(0)
.addService(ServerInterceptors.intercept(sampleService, new SampleContextServerInterceptor()))
.build()
.start();
this.channel = NettyChannelBuilder.forTarget("localhost:" + server.getPort())
.negotiationType(NegotiationType.PLAINTEXT)
.build();
this.client = ReactorToGrpcClientBuilder.newBuilder(SampleServiceReactorClient.class, SampleServiceGrpc.newStub(channel), SampleServiceGrpc.getServiceDescriptor(), SampleContext.class)
.withTimeout(TIMEOUT_DURATION)
.withStreamingTimeout(Duration.ofMillis(ReactorToGrpcClientBuilder.DEFAULT_STREAMING_TIMEOUT_MS))
.withGrpcStubDecorator(SampleContextServerInterceptor::attachClientContext)
.build();
}
private void createReactorGrpcServer(ReactorSampleServiceImpl reactorSampleService) throws Exception {
this.reactorSampleService = reactorSampleService;
DefaultGrpcToReactorServerFactory<SampleContext> factory = new DefaultGrpcToReactorServerFactory<>(SampleContext.class, SampleContextServerInterceptor::serverResolve);
ServerServiceDefinition serviceDefinition = factory.apply(SampleServiceGrpc.getServiceDescriptor(), reactorSampleService, ReactorSampleServiceImpl.class);
this.server = NettyServerBuilder.forPort(0)
.addService(ServerInterceptors.intercept(serviceDefinition, new SampleContextServerInterceptor()))
.build()
.start();
this.channel = NettyChannelBuilder.forTarget("localhost:" + server.getPort())
.negotiationType(NegotiationType.PLAINTEXT)
.build();
this.client = ReactorToGrpcClientBuilder.newBuilder(SampleServiceReactorClient.class, SampleServiceGrpc.newStub(channel), SampleServiceGrpc.getServiceDescriptor(), SampleContext.class)
.withTimeout(TIMEOUT_DURATION)
.withStreamingTimeout(Duration.ofMillis(ReactorToGrpcClientBuilder.DEFAULT_STREAMING_TIMEOUT_MS))
.withGrpcStubDecorator(SampleContextServerInterceptor::attachClientContext)
.build();
}
public static NettyServerBuilder getServerBuilder()
{
final NettyServerBuilder serverBuilder =
NettyServerBuilder.forAddress(new InetSocketAddress(getServerHost(), getServerPort()));
if (getBoolean(TLS))
{
final Path certificatesDir = Configuration.certificatesDirectory();
final SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(
certificatesDir.resolve("server.pem").toFile(), certificatesDir.resolve("server.key").toFile())
.trustManager(certificatesDir.resolve("ca.pem").toFile())
.clientAuth(ClientAuth.REQUIRE);
GrpcSslContexts.configure(sslClientContextBuilder);
try
{
serverBuilder.sslContext(sslClientContextBuilder.build());
}
catch (final SSLException ex)
{
LangUtil.rethrowUnchecked(ex);
}
}
return serverBuilder;
}
@Test
public void tcnative() throws Exception {
server = NettyServerBuilder.forPort(0)
.useTransportSecurity(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key"))
.addService(new SimpleServiceImpl())
.build().start();
channel = NettyChannelBuilder
.forAddress("localhost", server.getPort())
.sslContext(
GrpcSslContexts.configure(SslContextBuilder.forClient(), SslProvider.OPENSSL)
.trustManager(TestUtils.loadCert("ca.pem")).build())
.overrideAuthority("foo.test.google.fr")
.build();
SimpleServiceBlockingStub stub = SimpleServiceGrpc.newBlockingStub(channel);
assertThat(SimpleResponse.getDefaultInstance())
.isEqualTo(stub.unaryRpc(SimpleRequest.getDefaultInstance()));
}
public GrpcServer(int port) throws IOException {
workDir = new NamedTemporaryDirectory("__remote__");
GrpcRemoteExecutionServiceServer remoteExecution =
new GrpcRemoteExecutionServiceServer(
new LocalContentAddressedStorage(
workDir.getPath().resolve("__cache__"),
GrpcRemoteExecutionClients.PROTOCOL,
new DefaultBuckEventBus(new DefaultClock(true), new BuildId())),
workDir.getPath().resolve("__work__"));
NettyServerBuilder builder = NettyServerBuilder.forPort(port);
builder.maxMessageSize(500 * 1024 * 1024);
builder.withChildOption(ChannelOption.SO_REUSEADDR, true);
remoteExecution.getServices().forEach(builder::addService);
this.server = builder.build().start();
}
@Override
public void configure(ServerBuilder<?> serverBuilder) {
log.info("Grpc config: Configuring grpc {}", grpcProperties.getTls());
if (grpcProperties.getTls().isEnabled()) {
NettyServerBuilder nsb = (NettyServerBuilder) serverBuilder;
try {
nsb.sslContext(getSslContextBuilder().build());
} catch (Exception e) {
log.error("Grpc config: Error configuring ssl", e);
}
}
}
private void start() throws IOException {
NettyServerBuilder builder = NettyServerBuilder.forAddress(new InetSocketAddress(host, port))
.addService(serviceDefinition);
if (tlsEnabled) {
builder.sslContext(getSslContextBuilder().build());
}
server = builder.build().start();
logger.info("Server listening on " + port + "...");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
BrokerServer.this.stop();
}
});
}
public FateServerBuilder flowControlWindow(int count) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).flowControlWindow(count);
}
return this;
}
public FateServerBuilder keepAliveTime(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).keepAliveTime(count, timeUnit);
}
return this;
}
public FateServerBuilder keepAliveTimeout(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).keepAliveTimeout(count, timeUnit);
}
return this;
}
public FateServerBuilder permitKeepAliveTime(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).permitKeepAliveTime(count, timeUnit);
}
return this;
}
public FateServerBuilder permitKeepAliveWithoutCalls(boolean permit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).permitKeepAliveWithoutCalls(permit);
}
return this;
}
public FateServerBuilder maxConnectionIdle(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionIdle(count, timeUnit);
}
return this;
}
@Override
public void init(ServerConfig serverConfig) {
this.serverConfig = serverConfig;
server = NettyServerBuilder.forPort(serverConfig.getPort()).
fallbackHandlerRegistry(handlerRegistry)
.bossEventLoopGroup(constructBossEventLoopGroup())
.workerEventLoopGroup(constructWorkerEventLoopGroup())
.executor(initThreadPool(serverConfig))
.channelType(constructChannel())
.build();
}
@Override
protected NettyServerBuilder newServerBuilder() {
final String address = getAddress();
final int port = getPort();
if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
return NettyServerBuilder.forPort(port);
} else {
return NettyServerBuilder.forAddress(new InetSocketAddress(InetAddresses.forString(address), port));
}
}
@Override
// Keep this in sync with NettyGrpcServerFactory#configureKeepAlive
protected void configureKeepAlive(final NettyServerBuilder builder) {
if (this.properties.isEnableKeepAlive()) {
builder.keepAliveTime(this.properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(this.properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS);
}
builder.permitKeepAliveTime(this.properties.getPermitKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.permitKeepAliveWithoutCalls(this.properties.isPermitKeepAliveWithoutCalls());
}
@Override
protected NettyServerBuilder newServerBuilder() {
final String address = getAddress();
final int port = getPort();
if (GrpcServerProperties.ANY_IP_ADDRESS.equals(address)) {
return NettyServerBuilder.forPort(port);
} else {
return NettyServerBuilder.forAddress(new InetSocketAddress(InetAddresses.forString(address), port));
}
}
@Override
// Keep this in sync with NettyGrpcServerFactory#configureKeepAlive
protected void configureKeepAlive(final NettyServerBuilder builder) {
if (this.properties.isEnableKeepAlive()) {
builder.keepAliveTime(this.properties.getKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.keepAliveTimeout(this.properties.getKeepAliveTimeout().toNanos(), TimeUnit.NANOSECONDS);
}
builder.permitKeepAliveTime(this.properties.getPermitKeepAliveTime().toNanos(), TimeUnit.NANOSECONDS)
.permitKeepAliveWithoutCalls(this.properties.isPermitKeepAliveWithoutCalls());
}
@BeforeAll
static void setupServer() throws Exception {
server = NettyServerBuilder.forPort(0)
.addService(new TestService())
.build()
.start();
}
@Test
public void serviceLoaderFindsNetty() throws Exception {
assertThat(ServerBuilder.forPort(0)).isInstanceOf(NettyServerBuilder.class);
assertThat(ManagedChannelBuilder.forAddress("localhost", 1234))
.isInstanceOf(NettyChannelBuilder.class);
}
public FateServerBuilder maxConnectionAge(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionAge(count, timeUnit);
}
return this;
}
public FateServerBuilder maxConnectionAgeGrace(int count, TimeUnit timeUnit) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConnectionAgeGrace(count, timeUnit);
}
return this;
}
public EchoServer(final NettyServerBuilder serverBuilder)
{
server = serverBuilder.addService(new EchoService()).build();
}
@Test
public void serviceLoaderFindsNetty() throws Exception {
assertThat(ServerBuilder.forPort(0)).isInstanceOf(NettyServerBuilder.class);
assertThat(ManagedChannelBuilder.forAddress("localhost", 1234))
.isInstanceOf(NettyChannelBuilder.class);
}
@Override
protected ServerBuilder<?> builderForPort(int port) {
ServerBuilder<?> serverBuilder = NettyServerBuilder.forPort(port);
FateServerBuilder fateServerBuilder = new FateServerBuilder(serverBuilder);
return fateServerBuilder;
}
public FateServerBuilder maxConcurrentCallsPerConnection(int count) {
if (this.serverBuilder instanceof NettyServerBuilder) {
this.serverBuilder = ((NettyServerBuilder) this.serverBuilder).maxConcurrentCallsPerConnection(count);
}
return this;
}
public static FateServerBuilder forNettyServerBuilderAddress(SocketAddress socketAddress) {
return new FateServerBuilder(NettyServerBuilder.forAddress(socketAddress));
}