Java Code Examples for io.grpc.Server#awaitTermination()

The following examples show how to use io.grpc.Server#awaitTermination() . 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: InboundGRPCListener.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
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 2
Source File: StartCommand.java    From gauge-java with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws Exception {
    StaticScanner staticScanner = new StaticScanner();
    staticScanner.addStepsToRegistry();
    Server server;
    boolean multithreading = false;
    int stream = 1;
    String streamValue = System.getenv(STREAMS_COUNT_ENV);
    if (streamValue != null && !streamValue.isEmpty()) {
        stream = Integer.parseInt(streamValue);
        multithreading = true;
    }
    MessageProcessorFactory messageProcessorFactory = new MessageProcessorFactory(staticScanner);
    RunnerServiceHandler runnerServiceHandler = new RunnerServiceHandler(messageProcessorFactory, multithreading, stream);
    server = ServerBuilder.forPort(0).addService(runnerServiceHandler).executor((Executor) Runnable::run).build();
    runnerServiceHandler.addServer(server);
    server.start();
    int port = server.getPort();
    Logger.info("Listening on port:" + port);
    server.awaitTermination();
    System.exit(0);
}
 
Example 3
Source File: RxMetricsServer.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
  RxMetricsServiceGrpc.MetricsServiceImplBase service = new RxMetricsServiceGrpc.MetricsServiceImplBase() {

    @Override
    public Single<Streaming.Average> collect(Flowable<Streaming.Metric> request) {
      return request.map(m -> m.getMetric())
          .map(m -> new State(m, 1))
          .reduce((a, b) -> new State(a.sum + b.sum, a.count + b.count))
          .map(s -> Streaming.Average.newBuilder().setVal(s.sum / s.count).build())
          .toSingle();
    }
  };

  Server server = ServerBuilder.forPort(8080)
      .addService(service)
      .build();

  server.start();
  server.awaitTermination();
}
 
Example 4
Source File: ErrorHandlingClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
void run() throws Exception {
  // Port 0 means that the operating system will pick an available port to use.
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      responseObserver.onError(Status.INTERNAL
          .withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
    }
  }).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 5
Source File: GrpcServerHost.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 6
Source File: DetailErrorSample.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
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 7
Source File: KvRunner.java    From kvstore with Apache License 2.0 6 votes vote down vote up
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 8
Source File: GrpcServer.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 6 votes vote down vote up
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 9
Source File: DetailErrorSample.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
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 10
Source File: ErrorHandlingClient.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
void run() throws Exception {
  // Port 0 means that the operating system will pick an available port to use.
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      responseObserver.onError(Status.INTERNAL
          .withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
    }
  }).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 11
Source File: MyGrpcServer.java    From grpc-by-example-java with Apache License 2.0 5 votes vote down vote up
static public void main(String [] args) throws IOException, InterruptedException {
  Server server = ServerBuilder.forPort(8080)
      .addService(new GreetingServiceImpl()).build();

  System.out.println("Starting server...");
  server.start();
  System.out.println("Server started!");
  server.awaitTermination();
}
 
Example 12
Source File: EchoServer.java    From grpc-by-example-java with Apache License 2.0 5 votes vote down vote up
static public void main(String[] args) throws IOException, InterruptedException {

    Server server = ServerBuilder.forPort(8080)
        .addService(new EchoServiceImpl()).build();

    System.out.println("Starting server...");
    server.start();
    System.out.println("Server started!");
    server.awaitTermination();
  }
 
Example 13
Source File: GrpcServerHelper.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
/**
 * The following method shuts down an {@code Server} in two
 * phases, first by calling {@code shutdown} to reject incoming tasks,
 * and then calling {@code shutdownNow}, if necessary, to cancel any
 * lingering tasks.
 */
public static boolean shutdownAndAwaitTermination(final Server server, final long timeoutMillis) {
    if (server == null) {
        return true;
    }
    // disable new tasks from being submitted
    server.shutdown();
    final TimeUnit unit = TimeUnit.MILLISECONDS;
    final long phaseOne = timeoutMillis / 5;
    try {
        // wait a while for existing tasks to terminate
        if (server.awaitTermination(phaseOne, unit)) {
            return true;
        }
        server.shutdownNow();
        // wait a while for tasks to respond to being cancelled
        if (server.awaitTermination(timeoutMillis - phaseOne, unit)) {
            return true;
        }
        LOG.warn("Fail to shutdown grpc server: {}.", server);
    } catch (final InterruptedException e) {
        // (Re-)cancel if current thread also interrupted
        server.shutdownNow();
        // preserve interrupt status
        Thread.currentThread().interrupt();
    }
    return false;
}
 
Example 14
Source File: ContinuousBackpressureDemoServer.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = NettyServerBuilder
            .forPort(PORT)
            .addService(new ContinuousBackpressureDemoServer())
            .flowControlWindow(NettyServerBuilder.DEFAULT_FLOW_CONTROL_WINDOW)
            .build()
            .start();

    System.out.println("Listening on port 9999");
    server.awaitTermination();
}
 
Example 15
Source File: CompletableFutureEndToEndTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void serverRunsAndRespondsCorrectly() throws ExecutionException,
        IOException,
        InterruptedException,
        TimeoutException {
    final String name = UUID.randomUUID().toString();

    Server server = ServerBuilder.forPort(9999)
            .addService(new GreeterImpl())
            .build();

    server.start();

    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
            .usePlaintext(true)
            .build();

    GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel);

    CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());

    await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name));

    channel.shutdown();
    channel.awaitTermination(1, TimeUnit.MINUTES);
    channel.shutdownNow();

    server.shutdown();
    server.awaitTermination(1, TimeUnit.MINUTES);
    server.shutdownNow();
}
 
Example 16
Source File: PCSBasedOptimizerGrpcServer.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 17
Source File: CsiServer.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
@Override
public Void call() throws Exception {
  OzoneConfiguration ozoneConfiguration = createOzoneConfiguration();
  CsiConfig csiConfig = ozoneConfiguration.getObject(CsiConfig.class);

  OzoneClient rpcClient = OzoneClientFactory.getRpcClient(ozoneConfiguration);

  EpollEventLoopGroup group = new EpollEventLoopGroup();

  if (csiConfig.getVolumeOwner().isEmpty()) {
    throw new IllegalArgumentException(
        "ozone.csi.owner is not set. You should set this configuration "
            + "variable to define which user should own all the created "
            + "buckets.");
  }

  Server server =
      NettyServerBuilder
          .forAddress(new DomainSocketAddress(csiConfig.getSocketPath()))
          .channelType(EpollServerDomainSocketChannel.class)
          .workerEventLoopGroup(group)
          .bossEventLoopGroup(group)
          .addService(new IdentitiyService())
          .addService(new ControllerService(rpcClient,
              csiConfig.getDefaultVolumeSize()))
          .addService(new NodeService(csiConfig))
          .build();

  server.start();
  server.awaitTermination();
  rpcClient.close();
  return null;
}
 
Example 18
Source File: TestMain.java    From java-control-plane with Apache License 2.0 4 votes vote down vote up
/**
 * Example minimal xDS implementation using the java-control-plane lib.
 *
 * @param arg command-line args
 */
public static void main(String[] arg) throws IOException, InterruptedException {
  SimpleCache<String> cache = new SimpleCache<>(node -> GROUP);

  cache.setSnapshot(
      GROUP,
      Snapshot.create(
          ImmutableList.of(
              Cluster.newBuilder()
                  .setName("cluster0")
                  .setConnectTimeout(Duration.newBuilder().setSeconds(5))
                  .setType(DiscoveryType.STATIC)
                  .addHosts(Address.newBuilder()
                      .setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1234)))
                  .build()),
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableList.of(),
          "1"));

  DiscoveryServer discoveryServer = new DiscoveryServer(cache);

  ServerBuilder builder = NettyServerBuilder.forPort(12345)
      .addService(discoveryServer.getAggregatedDiscoveryServiceImpl())
      .addService(discoveryServer.getClusterDiscoveryServiceImpl())
      .addService(discoveryServer.getEndpointDiscoveryServiceImpl())
      .addService(discoveryServer.getListenerDiscoveryServiceImpl())
      .addService(discoveryServer.getRouteDiscoveryServiceImpl());

  Server server = builder.build();

  server.start();

  System.out.println("Server has started on port " + server.getPort());

  Runtime.getRuntime().addShutdownHook(new Thread(server::shutdown));

  Thread.sleep(10000);

  cache.setSnapshot(
      GROUP,
      Snapshot.create(
          ImmutableList.of(
              Cluster.newBuilder()
                  .setName("cluster1")
                  .setConnectTimeout(Duration.newBuilder().setSeconds(5))
                  .setType(DiscoveryType.STATIC)
                  .addHosts(Address.newBuilder()
                      .setSocketAddress(SocketAddress.newBuilder().setAddress("127.0.0.1").setPortValue(1235)))
                  .build()),
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableList.of(),
          "1"));

  server.awaitTermination();
}
 
Example 19
Source File: GrpcServer.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Start the server
    Server server = ServerBuilder.forPort(8888).addService(new GrpcServer()).build().start();
    server.awaitTermination();
}
 
Example 20
Source File: ChatServer.java    From grpc-by-example-java with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws InterruptedException, IOException {
  Server server = ServerBuilder.forPort(9090).addService(new ChatServiceImpl()).build();

  server.start();
  server.awaitTermination();
}