io.grpc.Server#awaitTermination ( )源码实例Demo

下面列出了io.grpc.Server#awaitTermination ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: micro-integrator   文件: InboundGRPCListener.java
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");
}
 
源代码2 项目: grpc-nebula-java   文件: ErrorHandlingClient.java
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();
}
 
源代码3 项目: grpc-nebula-java   文件: DetailErrorSample.java
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();
}
 
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();
  }
}
 
源代码5 项目: kvstore   文件: KvRunner.java
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");
}
 
源代码6 项目: grpc-java   文件: DetailErrorSample.java
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();
}
 
源代码7 项目: grpc-java-contrib   文件: GrpcServerHost.java
/**
 * 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;
        }
    }
}
 
源代码8 项目: grpc-java   文件: ErrorHandlingClient.java
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();
}
 
源代码9 项目: grpc-by-example-java   文件: RxMetricsServer.java
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();
}
 
源代码10 项目: gauge-java   文件: StartCommand.java
@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);
}
 
源代码11 项目: hadoop-ozone   文件: CsiServer.java
@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;
}
 
源代码12 项目: sofa-jraft   文件: GrpcServerHelper.java
/**
 * 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;
}
 
源代码13 项目: grpc-by-example-java   文件: EchoServer.java
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();
  }
 
源代码14 项目: grpc-by-example-java   文件: MyGrpcServer.java
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();
}
 
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();
}
 
@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();
}
 
源代码17 项目: AILibs   文件: PCSBasedOptimizerGrpcServer.java
/**
 * 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();

}
 
源代码18 项目: java-control-plane   文件: TestMain.java
/**
 * 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();
}
 
源代码19 项目: reactive-grpc   文件: GrpcServer.java
public static void main(String[] args) throws Exception {
    // Start the server
    Server server = ServerBuilder.forPort(8888).addService(new GrpcServer()).build().start();
    server.awaitTermination();
}
 
源代码20 项目: grpc-by-example-java   文件: ChatServer.java
public static void main(String[] args) throws InterruptedException, IOException {
  Server server = ServerBuilder.forPort(9090).addService(new ChatServiceImpl()).build();

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