Java Code Examples for io.grpc.ManagedChannel#shutdownNow()

The following examples show how to use io.grpc.ManagedChannel#shutdownNow() . 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: AndroidChannelBuilderTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
@Config(sdk = 23)
public void shutdownNowUnregistersBroadcastReceiver_api23() {
  TestChannel delegateChannel = new TestChannel();
  ManagedChannel androidChannel =
      new AndroidChannelBuilder.AndroidChannel(
          delegateChannel, ApplicationProvider.getApplicationContext());

  shadowOf(connectivityManager).setActiveNetworkInfo(null);
  ApplicationProvider
      .getApplicationContext()
      .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));
  androidChannel.shutdownNow();
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);
  ApplicationProvider
      .getApplicationContext()
      .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION));

  assertThat(delegateChannel.resetCount).isEqualTo(0);
}
 
Example 2
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void uncompressedClient_compressedEndpoint() throws Exception {
    final ManagedChannel nonDecompressingChannel =
            ManagedChannelBuilder.forAddress("127.0.0.1", server.httpPort())
                                 .decompressorRegistry(
                                         DecompressorRegistry.emptyInstance()
                                                             .with(Codec.Identity.NONE, false))
                                 .usePlaintext()
                                 .build();
    final UnitTestServiceBlockingStub client = UnitTestServiceGrpc.newBlockingStub(
            nonDecompressingChannel);
    assertThat(client.staticUnaryCallSetsMessageCompression(REQUEST_MESSAGE))
            .isEqualTo(RESPONSE_MESSAGE);
    nonDecompressingChannel.shutdownNow();

    checkRequestLog((rpcReq, rpcRes, grpcStatus) -> {
        assertThat(rpcReq.method()).isEqualTo(
                "armeria.grpc.testing.UnitTestService/StaticUnaryCallSetsMessageCompression");
        assertThat(rpcReq.params()).containsExactly(REQUEST_MESSAGE);
        assertThat(rpcRes.get()).isEqualTo(RESPONSE_MESSAGE);
    });
}
 
Example 3
Source File: AbstractUnaryGrpcServiceTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void normal_upstream() {
    final ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", server.httpPort())
                                                        .usePlaintext()
                                                        .build();

    try {
        final TestServiceBlockingStub stub = TestServiceGrpc.newBlockingStub(channel);

        assertThat(stub.unaryCall(SimpleRequest.newBuilder()
                                               .setPayload(Payload.newBuilder()
                                                                  .setBody(
                                                                          ByteString.copyFromUtf8("hello"))
                                                                  .build())
                                               .build()).getPayload().getBody().toStringUtf8())
                .isEqualTo("hello");
    } finally {
        channel.shutdownNow();
    }
}
 
Example 4
Source File: UcoreSender.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
public boolean renewLock(String sessionId) throws Exception {
    UcoreInterface.RenewSessionInput input = UcoreInterface.RenewSessionInput.newBuilder().setSessionId(sessionId).build();
    try {
        stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).renewSession(input);
        return true;
    } catch (Exception e1) {
        LOGGER.info("connect to ucore renew error and will retry");
        for (String ip : getIpList()) {
            ManagedChannel channel = null;
            try {
                channel = ManagedChannelBuilder.forAddress(ip,
                        Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
                stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).renewSession(input);
                return true;
            } catch (Exception e2) {
                LOGGER.info("connect to ucore renew error " + stub, e2);
                if (channel != null) {
                    channel.shutdownNow();
                }
            }
        }
        return false;
    }
}
 
Example 5
Source File: GrpcTracingIntegrationTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void integrationTest() throws Exception {
	ManagedChannel inProcessManagedChannel = this.clientManagedChannelBuilder
			.inProcessChannelBuilder("testServer").directExecutor().build();

	HelloServiceGrpcClient client = new HelloServiceGrpcClient(
			inProcessManagedChannel);

	assertThat(client.sayHello("Testy McTest Face"))
			.isEqualTo("Hello Testy McTest Face");
	assertThat(this.spans).hasSize(2);
	assertThat(this.spans.get(0).kind()).isEqualTo(Kind.SERVER);
	assertThat(this.spans.get(1).kind()).isEqualTo(Kind.CLIENT);

	// ManagedChannel does not implement Closeable...
	inProcessManagedChannel.shutdownNow();
}
 
Example 6
Source File: UcoreSender.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean alertResolve(ClusterAlertBean alert) {
    UcoreInterface.AlertInput input = getInput(alert);
    try {
        stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).alertResolve(input);
        return true;
    } catch (Exception e) {
        for (String ip : getIpList()) {
            ManagedChannel channel = null;
            try {
                channel = ManagedChannelBuilder.forAddress(ip, Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
                stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).alertResolve(input);
                return true;
            } catch (Exception e2) {
                LOGGER.info("alertResolve to ucore error ", e2);
                if (channel != null) {
                    channel.shutdownNow();
                }
                return false;
            }
        }
        return false;
    }
}
 
Example 7
Source File: ResumeStreamReactorDemo.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 8
Source File: ManagedChannelImplTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createResolvingOobChannel() throws Exception {
  String oobTarget = "fake://second.example.com";
  URI oobUri = new URI(oobTarget);
  channelBuilder
      .nameResolverFactory(new FakeNameResolverFactory.Builder(expectedUri, oobUri).build());
  createChannel();

  ManagedChannel resolvedOobChannel = null;
  try {
    resolvedOobChannel = helper.createResolvingOobChannel(oobTarget);

    assertWithMessage("resolving oob channel should have same authority")
        .that(resolvedOobChannel.authority())
        .isEqualTo(channel.authority());
  } finally {
    if (resolvedOobChannel != null) {
      resolvedOobChannel.shutdownNow();
    }
  }
}
 
Example 9
Source File: UcoreSender.java    From dble with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setKV(String path, String value) throws Exception {
    UcoreInterface.PutKvInput input = UcoreInterface.PutKvInput.newBuilder().setKey(path).setValue(value).build();
    try {
        stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).putKv(input);
    } catch (Exception e1) {
        for (String ip : getIpList()) {
            ManagedChannel channel = null;
            try {
                channel = ManagedChannelBuilder.forAddress(ip,
                        Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
                stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).putKv(input);
                return;
            } catch (Exception e2) {
                LOGGER.info("connect to ucore error ", e2);
                if (channel != null) {
                    channel.shutdownNow();
                }
            }
        }
        throw new IOException("ALL the ucore connect failure");
    }
}
 
Example 10
Source File: UcoreSender.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void cleanPath(String path) {
    if (!(path.charAt(path.length() - 1) == '/')) {
        path = path + "/";
    }
    UcoreInterface.DeleteKvTreeInput input = UcoreInterface.DeleteKvTreeInput.newBuilder().setKey(path).build();
    try {
        stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).deleteKvTree(input);
    } catch (Exception e1) {
        boolean flag = false;
        for (String ip : getIpList()) {
            ManagedChannel channel = null;
            try {
                channel = ManagedChannelBuilder.forAddress(ip,
                        Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
                stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).deleteKvTree(input);
                flag = true;
            } catch (Exception e2) {
                LOGGER.info("connect to ucore error ", e2);
                if (channel != null) {
                    channel.shutdownNow();
                }
            }
        }
        if (!flag) {
            throw new RuntimeException("ALL the ucore connect failure");
        }
    }
    cleanKV(path.substring(0, path.length() - 1));
}
 
Example 11
Source File: GrpcServiceServerTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void longMaxRequestLimit() throws Exception {
    final ManagedChannel channel =
            ManagedChannelBuilder.forAddress("127.0.0.1", serverWithLongMaxRequestLimit.httpPort())
                                 .usePlaintext()
                                 .build();
    try {
        final UnitTestServiceBlockingStub stub = UnitTestServiceGrpc.newBlockingStub(channel);
        assertThat(stub.staticUnaryCall(REQUEST_MESSAGE)).isEqualTo(RESPONSE_MESSAGE);
    } finally {
        channel.shutdownNow();
        requestLogQueue.take();
    }
}
 
Example 12
Source File: UcoreSender.java    From dble with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<KvBean> getKVPath(String path) {
    if (!(path.charAt(path.length() - 1) == '/')) {
        path = path + "/";
    }
    List<KvBean> result = new ArrayList<KvBean>();
    UcoreInterface.GetKvTreeInput input = UcoreInterface.GetKvTreeInput.newBuilder().setKey(path).build();

    UcoreInterface.GetKvTreeOutput output = null;

    try {
        output = stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).getKvTree(input);
    } catch (Exception e1) {
        for (String ip : getIpList()) {
            ManagedChannel channel = null;
            try {
                channel = ManagedChannelBuilder.forAddress(ip,
                        Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
                stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS);
                output = stub.withDeadlineAfter(GENERAL_GRPC_TIMEOUT, TimeUnit.SECONDS).getKvTree(input);
            } catch (Exception e2) {
                LOGGER.info("connect to ucore error ", e2);
                if (channel != null) {
                    channel.shutdownNow();
                }
            }
        }
    }
    if (output == null) {
        throw new RuntimeException("ALL the ucore connect failure");
    }
    for (int i = 0; i < output.getKeysCount(); i++) {
        KvBean bean = new KvBean(output.getKeys(i), output.getValues(i), output.getIndex());
        result.add(bean);
    }
    return result;
}
 
Example 13
Source File: ConnectionDetector.java    From mirror with Apache License 2.0 5 votes vote down vote up
private boolean isAvailable() {
  AtomicBoolean available = new AtomicBoolean(false);
  CountDownLatch done = new CountDownLatch(1);
  // We have to get a new channel on each successive attempt, as that's the only
  // way to really make a new connection attempt.
  ManagedChannel c = channelFactory.newChannel();
  try {
    MirrorStub stub = MirrorGrpc.newStub(c).withCompression("gzip");
    stub.withDeadlineAfter(deadlineDuration.toMillis(), MILLISECONDS).ping(PingRequest.newBuilder().build(), new StreamObserver<PingResponse>() {
      @Override
      public void onNext(PingResponse value) {
        available.set(true);
      }

      @Override
      public void onError(Throwable t) {
        done.countDown();
      }

      @Override
      public void onCompleted() {
        done.countDown();
      }
    });
    Utils.resetIfInterrupted(() -> done.await());
    return available.get();
  } finally {
    c.shutdownNow();
  }
}
 
Example 14
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 15
Source File: XdsTestClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
private void stop() throws InterruptedException {
  if (statsServer != null) {
    statsServer.shutdownNow();
    if (!statsServer.awaitTermination(5, TimeUnit.SECONDS)) {
      System.err.println("Timed out waiting for server shutdown");
    }
  }
  for (ManagedChannel channel : channels) {
    channel.shutdownNow();
  }
  if (exec != null) {
    exec.shutdownNow();
  }
}
 
Example 16
Source File: HandshakerServiceChannel.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored") // netty ChannelFuture
public void close(ManagedChannel instance) {
  instance.shutdownNow();
  if (eventGroup != null) {
    eventGroup.shutdownGracefully();
  }
}
 
Example 17
Source File: AndroidChannelBuilderTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
@Config(sdk = 24)
public void shutdownNowUnregistersNetworkCallback_api24() {
  shadowOf(connectivityManager).setActiveNetworkInfo(null);
  TestChannel delegateChannel = new TestChannel();
  ManagedChannel androidChannel =
      new AndroidChannelBuilder.AndroidChannel(
          delegateChannel, RuntimeEnvironment.application.getApplicationContext());

  androidChannel.shutdownNow();
  shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED);

  assertThat(delegateChannel.resetCount).isEqualTo(0);
}
 
Example 18
Source File: LoadBalanceContextBuilderTest.java    From servicecomb-pack with Apache License 2.0 4 votes vote down vote up
private void shutdownChannels(LoadBalanceContext loadContext) {
  for (ManagedChannel each : loadContext.getChannels()) {
    each.shutdownNow();
  }
}
 
Example 19
Source File: TaskRelocationSandbox.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public void shutdown() {
    for (ManagedChannel channel : channels) {
        channel.shutdownNow();
    }
    container.close();
}
 
Example 20
Source File: NettyChannelBuilderTest.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
private void shutdown(ManagedChannel mc) throws Exception {
  mc.shutdownNow();
  assertTrue(mc.awaitTermination(1, TimeUnit.SECONDS));
}