io.grpc.Server Java Examples
The following examples show how to use
io.grpc.Server.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntrospectionAutoConfiguration.java From genie with Apache License 2.0 | 6 votes |
/** * Provide a {@link GenieWebRpcInfo} bean if one hasn't already been defined. * * @param server The gRPC {@link Server} instance. Must not be {@link Server#isShutdown()} or * {@link Server#isTerminated()}. Must be able to get the port the server is listening on. * @return A {@link GenieWebRpcInfo} instance * @throws IllegalStateException When an instance can't be created */ @Bean @ConditionalOnMissingBean( { GenieWebRpcInfo.class } ) public GenieWebRpcInfo genieWebRpcInfo(final Server server) throws IllegalStateException { if (server.isShutdown() || server.isTerminated()) { throw new IllegalStateException("gRPC server is already shut down. Can't start."); } else { final int port = GRpcServerUtils.startServer(server); if (port < 1) { throw new IllegalStateException("gRPC server started on illegal port: " + port); } return new GenieWebRpcInfo(port); } }
Example #2
Source File: ServerWatcherRunnable.java From bazel with Apache License 2.0 | 6 votes |
@VisibleForTesting ServerWatcherRunnable( Server server, long maxIdleSeconds, boolean shutdownOnLowSysMem, CommandManager commandManager, LowMemoryChecker lowMemoryChecker) { Preconditions.checkArgument( maxIdleSeconds > 0, "Expected to only check idleness when --max_idle_secs > 0 but it was %s", maxIdleSeconds); this.server = server; this.maxIdleSeconds = maxIdleSeconds; this.commandManager = commandManager; this.lowMemoryChecker = lowMemoryChecker; this.shutdownOnLowSysMem = shutdownOnLowSysMem; }
Example #3
Source File: GrpcCleanupRuleTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
@Test public void singleServerCleanup() throws Throwable { // setup Server server = mock(Server.class); Statement statement = mock(Statement.class); InOrder inOrder = inOrder(statement, server); GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); // run grpcCleanup.register(server); boolean awaitTerminationFailed = false; try { // will throw because channel.awaitTermination(long, TimeUnit) will return false; grpcCleanup.apply(statement, null /* description*/).evaluate(); } catch (AssertionError e) { awaitTerminationFailed = true; } // verify assertTrue(awaitTerminationFailed); inOrder.verify(statement).evaluate(); inOrder.verify(server).shutdown(); inOrder.verify(server).awaitTermination(anyLong(), any(TimeUnit.class)); inOrder.verify(server).shutdownNow(); }
Example #4
Source File: AgentRpcServersAutoConfigurationTest.java From genie with Apache License 2.0 | 6 votes |
/** * User beans override default beans. */ @Test void expectedBeansExistWhenUserOverrides() { this.contextRunner .withUserConfiguration(UserConfig.class) .run( context -> { Assertions.assertThat(context).hasSingleBean(GRpcServerProperties.class); Assertions.assertThat(context).hasSingleBean(Server.class); Assertions.assertThat(context).hasSingleBean(GRpcServerManager.class); Assertions.assertThat(context.containsBean("userServer")).isTrue(); Assertions.assertThat(context.containsBean("userServerManager")).isTrue(); Assertions.assertThat(context.containsBean("gRpcServer")).isFalse(); Assertions.assertThat(context.containsBean("gRpcServerManager")).isFalse(); } ); }
Example #5
Source File: GRPCConfigurationTest.java From liiklus with MIT License | 6 votes |
@Test void shouldConsiderTransportConfigurers() { var service = ServerServiceDefinition.builder("test").build(); new ApplicationContextRunner() .withInitializer((ApplicationContextInitializer) new GRPCConfiguration()) .withPropertyValues( "spring.profiles.active: gateway", "grpc.port: 0" ) .withInitializer(ctx -> { var context = (GenericApplicationContext) ctx; context.registerBean(LiiklusService.class, () -> Mockito.mock(LiiklusService.class)); context.registerBean(GRPCLiiklusTransportConfigurer.class, () -> builder -> builder.addService(() -> service)); }) .run(context -> { assertThat(context).getBeans(GRPCLiiklusTransportConfigurer.class).isNotEmpty(); assertThat(context) .getBean(Server.class) .satisfies(server -> { assertThat(server.getServices()).contains(service); }); }); }
Example #6
Source File: RemoteWorker.java From bazel with Apache License 2.0 | 6 votes |
public Server startServer() throws IOException { ServerInterceptor headersInterceptor = new TracingMetadataUtils.ServerHeadersInterceptor(); NettyServerBuilder b = NettyServerBuilder.forPort(workerOptions.listenPort) .addService(ServerInterceptors.intercept(actionCacheServer, headersInterceptor)) .addService(ServerInterceptors.intercept(bsServer, headersInterceptor)) .addService(ServerInterceptors.intercept(casServer, headersInterceptor)) .addService(ServerInterceptors.intercept(capabilitiesServer, headersInterceptor)); if (workerOptions.tlsCertificate != null) { b.sslContext(getSslContextBuilder(workerOptions).build()); } if (execServer != null) { b.addService(ServerInterceptors.intercept(execServer, headersInterceptor)); } else { logger.atInfo().log("Execution disabled, only serving cache requests"); } Server server = b.build(); logger.atInfo().log("Starting gRPC server on port %d", workerOptions.listenPort); server.start(); return server; }
Example #7
Source File: GrpcServer.java From glowroot with Apache License 2.0 | 6 votes |
private static Server startServer(String bindAddress, int port, boolean https, File confDir, @Nullable ExecutorService confDirWatchExecutor, DownstreamServiceImpl downstreamService, CollectorServiceImpl collectorService) throws IOException { NettyServerBuilder builder = NettyServerBuilder.forAddress(new InetSocketAddress(bindAddress, port)); if (https) { builder.sslContext( DelegatingSslContext.create(confDir, checkNotNull(confDirWatchExecutor))); } return builder.addService(collectorService.bindService()) .addService(downstreamService.bindService()) // need to override default max message size of 4mb until streaming is implemented // for DownstreamService.EntriesResponse and FullTraceResponse .maxInboundMessageSize(64 * 1024 * 1024) // aggressive keep alive is used by agent to detect silently dropped connections // (see org.glowroot.agent.central.CentralConnection) .permitKeepAliveTime(20, SECONDS) // aggressive max connection age forces agents to re-resolve DNS often for DNS-based // load balancing (e.g. to pick up and spread load across new central collectors) .maxConnectionAge(20, MINUTES) .build() .start(); }
Example #8
Source File: GrpcServerHost.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Shutdown the gRPC {@link Server} when this object is closed. */ @Override public void close() throws Exception { final Server server = server(); if (server != null) { server.shutdown(); try { // TODO: Maybe we should catch the InterruptedException from this? server.awaitTermination(shutdownWaitTimeInMillis, TimeUnit.MILLISECONDS); } finally { server.shutdownNow(); this.server = null; } } }
Example #9
Source File: GrpcClientTest.java From cloud-spanner-r2dbc with Apache License 2.0 | 6 votes |
/** * Starts and shuts down an in-process gRPC service based on the {@code serviceImpl} provided, * while allowing a test to execute using the {@link GrpcClient}. * * @param serviceImpl implementation of the Spanner service. Typically, just the methods needed to * execute the test. * @param clientConsumer consumer of the {@link GrpcClient} - the class under test. * @return a Mockito spy for the gRPC service for verification. */ private SpannerImplBase doTest(SpannerGrpc.SpannerImplBase serviceImpl, Consumer<GrpcClient> clientConsumer) throws IOException { SpannerGrpc.SpannerImplBase serviceImplSpy = spy(serviceImpl); String serverName = InProcessServerBuilder.generateName(); Server server = InProcessServerBuilder .forName(serverName).directExecutor().addService(serviceImplSpy).build().start(); ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); clientConsumer.accept(new GrpcClient(SpannerGrpc.newStub(channel), null, null)); channel.shutdown(); server.shutdown(); return serviceImplSpy; }
Example #10
Source File: GrpcServerHostTest.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void startDoesNotStartServerWithoutServices() throws Exception { final int port = ThreadLocalRandom.current().nextInt(1000, 10000); final long shutdownWaitTimeInMillis = ThreadLocalRandom.current().nextLong(1000, 10000); final ApplicationContext applicationContext = mock(ApplicationContext.class); final Server server = mock(Server.class, new TriesToReturnSelf()); final GrpcServerFactory factory = mock(GrpcServerFactory.class); when(server.getPort()).thenReturn(port); // Configure application context to contain no gRPC services. when(applicationContext.getBeansWithAnnotation(eq(GrpcService.class))).thenReturn(ImmutableMap.of()); GrpcServerHost runner = new GrpcServerHost(port, shutdownWaitTimeInMillis, factory); runner.setApplicationContext(applicationContext); assertThatThrownBy(runner::start).isInstanceOf(IOException.class); // Make sure the server builder was not used. verify(factory, never()).buildServerForServices(anyInt(), any()); assertThat(runner.server()).isNull(); }
Example #11
Source File: GrpcCleanupRuleTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void singleServerCleanup() throws Throwable { // setup Server server = mock(Server.class); Statement statement = mock(Statement.class); InOrder inOrder = inOrder(statement, server); GrpcCleanupRule grpcCleanup = new GrpcCleanupRule(); // run grpcCleanup.register(server); boolean awaitTerminationFailed = false; try { // will throw because channel.awaitTermination(long, TimeUnit) will return false; grpcCleanup.apply(statement, null /* description*/).evaluate(); } catch (AssertionError e) { awaitTerminationFailed = true; } // verify assertTrue(awaitTerminationFailed); inOrder.verify(statement).evaluate(); inOrder.verify(server).shutdown(); inOrder.verify(server).awaitTermination(anyLong(), any(TimeUnit.class)); inOrder.verify(server).shutdownNow(); }
Example #12
Source File: KvRunner.java From kvstore with Apache License 2.0 | 6 votes |
private void stopServer() throws InterruptedException { Server s = server; if (s == null) { throw new IllegalStateException("Already stopped"); } server = null; s.shutdown(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { return; } s.shutdownNow(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { return; } throw new RuntimeException("Unable to shutdown server"); }
Example #13
Source File: ResumeStreamReactorDemo.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 6 votes |
public static void main(String[] args) throws Exception { Server server = InProcessServerBuilder .forName("ResumeStreamReactorDemo") .addService(new FlakyNumberService()) .build() .start(); ManagedChannel channel = InProcessChannelBuilder .forName("ResumeStreamReactorDemo") .usePlaintext() .build(); ReactorNumbersGrpc.ReactorNumbersStub stub = ReactorNumbersGrpc.newReactorStub(channel); // Keep retrying the stream until you get ten in a row with no error new GrpcRetryFlux<>(() -> stub.oneToMany(Mono.just(Message.getDefaultInstance()))) .map(Message::getNumber) .subscribe(System.out::println); Thread.sleep(TimeUnit.SECONDS.toMillis(1)); channel.shutdownNow(); server.shutdownNow(); }
Example #14
Source File: DetailErrorSample.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
void run() throws Exception { Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { Metadata trailers = new Metadata(); trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO); responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC) .asRuntimeException(trailers)); } }).build().start(); channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build(); blockingCall(); futureCallDirect(); futureCallCallback(); asyncCall(); advancedAsyncCall(); channel.shutdown(); server.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); server.awaitTermination(); }
Example #15
Source File: GrpcServer.java From Mastering-Microservices-with-Java-Third-Edition with MIT License | 6 votes |
public static void main(String[] arg) { try { Server server = ServerBuilder.forPort(8080) .addService(new EmployeeService()) .build(); System.out.println("Starting gRPC Server Service ..."); server.start(); System.out.println("Server has started at port: 8080"); System.out.println("Following services are available: "); server.getServices().stream() .forEach( s -> System.out.println("Service Name: " + s.getServiceDescriptor().getName()) ); server.awaitTermination(); } catch (Exception e) { e.printStackTrace(); } }
Example #16
Source File: InboundGRPCListener.java From micro-integrator with Apache License 2.0 | 6 votes |
public void stop() throws InterruptedException { Server s = server; if (s == null) { throw new IllegalStateException("gRPC Listener Server is already stopped"); } server = null; s.shutdown(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { log.debug("gRPC Listener Server stopped"); return; } s.shutdownNow(); if (s.awaitTermination(1, TimeUnit.SECONDS)) { return; } throw new RuntimeException("Unable to shutdown gRPC Listener Server"); }
Example #17
Source File: IntrospectionAutoConfigurationTest.java From genie with Apache License 2.0 | 5 votes |
@Bean Server mockGRpcServer() { final Server server = Mockito.mock(Server.class); Mockito.when(server.isTerminated()).thenReturn(true); Mockito.when(server.isShutdown()).thenReturn(false); return server; }
Example #18
Source File: Application.java From grpc-by-example-java with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws IOException, InterruptedException { Server server = ServerBuilder.forPort(8081) .addService(new GreetingServiceImpl()) .build(); server.start(); server.awaitTermination(); }
Example #19
Source File: StackdriverTraceAutoConfigurationTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Bean(destroyMethod = "shutdownNow") Server server(GcpTraceService gcpTraceService) throws IOException { return InProcessServerBuilder.forName(GRPC_SERVER_NAME) .addService(gcpTraceService) .directExecutor() .build().start(); }
Example #20
Source File: ChannelFactoryTest.java From pinpoint with Apache License 2.0 | 5 votes |
private static Server serverStart(ExecutorService executorService) throws IOException { logger.debug("server start"); serverFactory = new ServerFactory(ChannelFactoryTest.class.getSimpleName() + "-server", "127.0.0.1", PORT, executorService, new ServerOption.Builder().build()); spanService = new SpanService(); serverFactory.addService(spanService); addFilter(serverFactory); Server server = serverFactory.build(); return server; }
Example #21
Source File: ServerFactory.java From pinpoint with Apache License 2.0 | 5 votes |
public Server build() { InetSocketAddress bindAddress = new InetSocketAddress(this.hostname, this.port); NettyServerBuilder serverBuilder = NettyServerBuilder.forAddress(bindAddress); serverBuilder.bossEventLoopGroup(bossEventLoopGroup); serverBuilder.workerEventLoopGroup(workerEventLoopGroup); setupInternal(serverBuilder); for (Object service : this.bindableServices) { if (service instanceof BindableService) { logger.info("Add BindableService={}, server={}", service, name); serverBuilder.addService((BindableService) service); } else if (service instanceof ServerServiceDefinition) { final ServerServiceDefinition definition = (ServerServiceDefinition) service; logger.info("Add ServerServiceDefinition={}, server={}", definition.getServiceDescriptor(), name); serverBuilder.addService(definition); } } for (ServerTransportFilter transportFilter : this.serverTransportFilters) { logger.info("Add transportFilter={}, server={}", transportFilter, name); serverBuilder.addTransportFilter(transportFilter); } for (ServerInterceptor serverInterceptor : this.serverInterceptors) { logger.info("Add intercept={}, server={}", serverInterceptor, name); serverBuilder.intercept(serverInterceptor); } serverBuilder.executor(serverExecutor); setupServerOption(serverBuilder); Server server = serverBuilder.build(); return server; }
Example #22
Source File: GrpcITest.java From java-specialagent with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws InterruptedException, IOException { final CountDownLatch latch = TestUtil.initExpectedSpanLatch(2); final Server server = ServerBuilder.forPort(8086).addService(new GreeterImpl()).build().start(); final ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8086).usePlaintext(true).build(); final GreeterBlockingStub greeterBlockingStub = GreeterGrpc.newBlockingStub(channel); greeterBlockingStub.sayHello(HelloRequest.newBuilder().setName("world").build()).getMessage(); server.shutdownNow(); TestUtil.checkSpan(latch, new ComponentSpanCount("java-grpc", 2) ); }
Example #23
Source File: GrpcServerLifecycle.java From grpc-spring-boot-starter with MIT License | 5 votes |
/** * Initiates an orderly shutdown of the grpc server and releases the references to the server. This call does not * wait for the server to be completely shut down. */ protected void stopAndReleaseGrpcServer() { final Server localServer = this.server; if (localServer != null) { localServer.shutdown(); this.server = null; log.info("gRPC server shutdown."); } }
Example #24
Source File: BackpressureController.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 5 votes |
@FXML public void initialize() throws Exception { Server server = ServerBuilder.forPort(9000).addService(this).build().start(); Channel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build(); stub = RxBackpressureDemoGrpc.newRxStub(channel); producedSeries.setName("Produced"); consumedSeries.setName("Consumed"); lineChart.getData().add(producedSeries); lineChart.getData().add(consumedSeries); }
Example #25
Source File: HelloServiceServer.java From grpc-swagger with MIT License | 5 votes |
public static void main(String[] args) throws Exception { logger.info("Starting server on port " + DEMO_SERVER_PORT); Server server = ServerBuilder.forPort(DEMO_SERVER_PORT) .addService(ProtoReflectionService.newInstance()) .addService(new HelloServiceImpl()) .build() .start(); server.awaitTermination(); }
Example #26
Source File: ServerWrapperForXds.java From grpc-java with Apache License 2.0 | 5 votes |
@Override public Server start() throws IOException { delegate.start(); if (!xdsClientWrapperForServerSds.hasXdsClient()) { xdsClientWrapperForServerSds.createXdsClientAndStart(); } return this; }
Example #27
Source File: FateServer.java From FATE-Serving with Apache License 2.0 | 5 votes |
@Override public Server start() throws IOException { Server server =this.server.start(); // register(); return this; }
Example #28
Source File: PCSBasedOptimizerGrpcServer.java From AILibs with GNU Affero General Public License v3.0 | 5 votes |
/** * main method (and init()) is not actually needed, but helpful for debugging * purposes * * @param args * @throws Exception */ public static void main(final String[] args) throws Exception { init(); Server server = ServerBuilder.forPort(8080).addService(new PCSBasedOptimizerServiceImpl(evaluator, input)).build(); server.start(); server.awaitTermination(); }
Example #29
Source File: HelloServiceServer.java From grpc-swagger with MIT License | 5 votes |
public static void main(String[] args) throws Exception { logger.info("Starting server on port " + DEMO_SERVER_PORT); Server server = ServerBuilder.forPort(DEMO_SERVER_PORT) .addService(ProtoReflectionService.newInstance()) .addService(new HelloServiceImpl()) .build() .start(); server.awaitTermination(); }
Example #30
Source File: LoadBalancedClusterMessageSenderTest.java From txle with Apache License 2.0 | 5 votes |
private static void startServerOnPort(int port) { ServerBuilder<?> serverBuilder = ServerBuilder.forPort(port); serverBuilder.addService(new MyTxEventService(connected.get(port), eventsMap.get(port), delays.get(port))); Server server = serverBuilder.build(); try { server.start(); servers.put(port, server); } catch (IOException e) { fail(e.getMessage()); } }