Java Code Examples for io.grpc.ManagedChannel#shutdown()
The following examples show how to use
io.grpc.ManagedChannel#shutdown() .
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: ClientConnectionManager.java From jetcd with Apache License 2.0 | 8 votes |
<T extends AbstractStub<T>, R> CompletableFuture<R> withNewChannel(URI endpoint, Function<ManagedChannel, T> stubCustomizer, Function<T, CompletableFuture<R>> stubConsumer) { final ManagedChannel channel = defaultChannelBuilder().nameResolverFactory( forEndpoints( Util.supplyIfNull(builder.authority(), () -> ""), Collections.singleton(endpoint), Util.supplyIfNull(builder.uriResolverLoader(), URIResolverLoader::defaultLoader))) .build(); try { T stub = stubCustomizer.apply(channel); return stubConsumer.apply(stub).whenComplete((r, t) -> channel.shutdown()); } catch (Exception e) { channel.shutdown(); throw EtcdExceptionFactory.toEtcdException(e); } }
Example 2
Source File: GrpcChannelScope.java From micronaut-grpc with Apache License 2.0 | 6 votes |
@Override @PreDestroy public void close() { for (ManagedChannel channel : channels.values()) { if (!channel.isShutdown()) { try { channel.shutdown(); } catch (Exception e) { if (LOG.isWarnEnabled()) { LOG.warn("Error shutting down GRPC channel: " + e.getMessage(), e); } } } } channels.clear(); }
Example 3
Source File: MyGrpcClient.java From grpc-by-example-java with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080) .usePlaintext(true) .build(); GreetingServiceGrpc.GreetingServiceBlockingStub stub = GreetingServiceGrpc.newBlockingStub(channel); HelloResponse helloResponse = stub.greeting( HelloRequest.newBuilder() .setName("Ray") .setAge(18) .setSentiment(Sentiment.HAPPY) .build()); System.out.println(helloResponse); channel.shutdown(); }
Example 4
Source File: ManagedChannelImplTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Test public void oobChannelsNoConnectionShutdown() { createChannel(); ManagedChannel oob1 = helper.createOobChannel(addressGroup, "oob1Authority"); ManagedChannel oob2 = helper.createOobChannel(addressGroup, "oob2Authority"); channel.shutdown(); verify(mockLoadBalancer).shutdown(); oob1.shutdown(); assertTrue(oob1.isTerminated()); assertFalse(channel.isTerminated()); oob2.shutdown(); assertTrue(oob2.isTerminated()); assertTrue(channel.isTerminated()); verify(mockTransportFactory, never()) .newClientTransport( any(SocketAddress.class), any(ClientTransportOptions.class), any(ChannelLogger.class)); }
Example 5
Source File: ManagedChannelUtils.java From pinpoint with Apache License 2.0 | 6 votes |
public static boolean shutdownManagedChannel(String name, ManagedChannel managedChannel, long timeout, TimeUnit unit) { if (managedChannel == null) { return false; } logger.debug("shutdown {}", name); managedChannel.shutdown(); try { final boolean success = managedChannel.awaitTermination(timeout, unit); if (!success) { logger.warn("shutdown timeout {}", name); } return success; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
Example 6
Source File: Utils.java From dropwizard-grpc with Apache License 2.0 | 5 votes |
/** * Shuts down the given channel if not <code>null</code>, waiting for up to 1 second. * * @param channel the channel to shut down */ public static void shutdownChannel(final ManagedChannel channel) { if (channel != null) { channel.shutdown(); try { channel.awaitTermination(1, TimeUnit.SECONDS); } catch (final InterruptedException e) { // silently swallow exception } } }
Example 7
Source File: BaseITTracingClientInterceptor.java From brave with Apache License 2.0 | 5 votes |
void closeClient(ManagedChannel client) { client.shutdown(); try { client.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(e); } }
Example 8
Source File: KubernetesRuntime.java From pulsar with Apache License 2.0 | 5 votes |
@Override public void stop() throws Exception { deleteStatefulSet(); deleteService(); if (channel != null) { for (ManagedChannel cn : channel) { cn.shutdown(); } } channel = null; stub = null; }
Example 9
Source File: AndroidChannelBuilderTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Test @Config(sdk = 24) public void nullContextDoesNotThrow_api24() { shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED); TestChannel delegateChannel = new TestChannel(); ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, null); // Network change and shutdown should be no-op for the channel without an Android Context shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); androidChannel.shutdown(); assertThat(delegateChannel.resetCount).isEqualTo(0); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); }
Example 10
Source File: ManagedChannelHelper.java From sofa-jraft with Apache License 2.0 | 5 votes |
/** * The following method shuts down an {@code ManagedChannel} 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 ManagedChannel mChannel, final long timeoutMillis) { if (mChannel == null) { return true; } // disable new tasks from being submitted mChannel.shutdown(); final TimeUnit unit = TimeUnit.MILLISECONDS; final long phaseOne = timeoutMillis / 5; try { // wait a while for existing tasks to terminate if (mChannel.awaitTermination(phaseOne, unit)) { return true; } mChannel.shutdownNow(); // wait a while for tasks to respond to being cancelled if (mChannel.awaitTermination(timeoutMillis - phaseOne, unit)) { return true; } LOG.warn("Fail to shutdown managed channel: {}.", mChannel); } catch (final InterruptedException e) { // (Re-)cancel if current thread also interrupted mChannel.shutdownNow(); // preserve interrupt status Thread.currentThread().interrupt(); } return false; }
Example 11
Source File: Executor.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { String host = args[0]; String instanceName = args[1]; String blobsDir; if (args.length == 3) { blobsDir = args[2]; } else { blobsDir = null; } Scanner scanner = new Scanner(System.in); ImmutableList.Builder<Digest> actionDigests = ImmutableList.builder(); while (scanner.hasNext()) { actionDigests.add(DigestUtil.parseDigest(scanner.nextLine())); } ManagedChannel channel = createChannel(host); if (blobsDir != null) { System.out.println("Loading blobs into cas"); loadFilesIntoCAS(instanceName, channel, Paths.get(blobsDir)); } ExecutionStub execStub = ExecutionGrpc.newStub(channel); executeActions(instanceName, actionDigests.build(), execStub); channel.shutdown(); channel.awaitTermination(1, SECONDS); }
Example 12
Source File: Http2OkHttpTest.java From grpc-java with Apache License 2.0 | 5 votes |
@Test public void hostnameVerifierWithCorrectHostname() throws Exception { int port = ((InetSocketAddress) getListenAddress()).getPort(); ManagedChannel channel = createChannelBuilder() .overrideAuthority(GrpcUtil.authorityFromHostAndPort( TestUtils.TEST_SERVER_HOST, port)) .hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return false; } }) .build(); TestServiceGrpc.TestServiceBlockingStub blockingStub = TestServiceGrpc.newBlockingStub(channel); Throwable actualThrown = null; try { blockingStub.emptyCall(Empty.getDefaultInstance()); } catch (Throwable t) { actualThrown = t; } assertNotNull("The rpc should have been failed due to hostname verification", actualThrown); Throwable cause = Throwables.getRootCause(actualThrown); assertTrue( "Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException); channel.shutdown(); }
Example 13
Source File: AndroidChannelBuilderTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test @Config(sdk = 24) public void resetConnectBackoffAndEnterIdle_api24() { shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED); TestChannel delegateChannel = new TestChannel(); ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel( delegateChannel, RuntimeEnvironment.application.getApplicationContext()); assertThat(delegateChannel.resetCount).isEqualTo(0); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); // Establish an initial network connection shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); // Switch to another network to trigger enterIdle() shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Switch to an offline network and then to null shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_DISCONNECTED); shadowOf(connectivityManager).setActiveNetworkInfo(null); assertThat(delegateChannel.resetCount).isEqualTo(1); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Establish a connection shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(2); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); // Disconnect, then shutdown the channel and verify that the callback has been unregistered shadowOf(connectivityManager).setActiveNetworkInfo(null); androidChannel.shutdown(); shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); assertThat(delegateChannel.resetCount).isEqualTo(2); assertThat(delegateChannel.enterIdleCount).isEqualTo(1); }
Example 14
Source File: AndroidChannelBuilderTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@Test @Config(sdk = 24) public void nullContextDoesNotThrow_api24() { shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED); TestChannel delegateChannel = new TestChannel(); ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel(delegateChannel, null); // Network change and shutdown should be no-op for the channel without an Android Context shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); androidChannel.shutdown(); assertThat(delegateChannel.resetCount).isEqualTo(0); assertThat(delegateChannel.enterIdleCount).isEqualTo(0); }
Example 15
Source File: DeviceUnlockedBroadcastReceiver.java From capillary with Apache License 2.0 | 5 votes |
@Override public void onReceive(Context context, Intent intent) { // Check if this is the right intent action. if (!Intent.ACTION_USER_PRESENT.equals(intent.getAction())) { return; } try { Utils.initialize(context); // Create the gRPC channel. ManagedChannel channel = Utils.createGrpcChannel(context); // Create the DemoCapillaryHandler. DemoCapillaryHandler handler = new DemoCapillaryHandler(context, channel); // Process any saved RsaEcdsa ciphertexts. Utils.getKeyManager(context, KeyAlgorithm.RSA_ECDSA) .getDecrypterManager().decryptSaved(handler, KeyAlgorithm.RSA_ECDSA); // Process any saved WebPush ciphertexts. Utils.getKeyManager(context, KeyAlgorithm.WEB_PUSH) .getDecrypterManager().decryptSaved(handler, KeyAlgorithm.WEB_PUSH); // Close the gRPC channel. channel.shutdown(); } catch (GeneralSecurityException | IOException e) { e.printStackTrace(); } }
Example 16
Source File: UsePubSubEmulatorSnippet.java From google-cloud-java with Apache License 2.0 | 5 votes |
public static void main(String... args) throws IOException { // [START pubsub_use_emulator] String hostport = System.getenv("PUBSUB_EMULATOR_HOST"); ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build(); try { TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel)); CredentialsProvider credentialsProvider = NoCredentialsProvider.create(); // Set the channel and credentials provider when creating a `TopicAdminClient`. // Similarly for SubscriptionAdminClient TopicAdminClient topicClient = TopicAdminClient.create( TopicAdminSettings.newBuilder() .setTransportChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build()); TopicName topicName = TopicName.of("my-project-id", "my-topic-id"); // Set the channel and credentials provider when creating a `Publisher`. // Similarly for Subscriber Publisher publisher = Publisher.newBuilder(topicName) .setChannelProvider(channelProvider) .setCredentialsProvider(credentialsProvider) .build(); } finally { channel.shutdown(); } // [END pubsub_use_emulator] }
Example 17
Source File: ChatClient.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 4 votes |
public static void main(String[] args) throws Exception { String author = args.length == 0 ? "Random_Stranger" : args[0]; // Connect to the sever ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", PORT).usePlaintext().build(); RxChatGrpc.RxChatStub stub = RxChatGrpc.newRxStub(channel); CountDownLatch done = new CountDownLatch(1); ConsoleReader console = new ConsoleReader(); console.println("Type /quit to exit"); /* ****************************** * Subscribe to incoming messages * ******************************/ disposables.add(Single.just(Empty.getDefaultInstance()) .as(stub::getMessages) .filter(message -> !message.getAuthor().equals(author)) .subscribe(message -> printLine(console, message.getAuthor(), message.getMessage()))); /* ************************* * Publish outgoing messages * *************************/ disposables.add(Observable // Send connection message .just(author + " joined.") // Send user input .concatWith(Observable.fromIterable(new ConsoleIterator(console, author + " > "))) // Send disconnect message .concatWith(Single.just(author + " left.")) .map(msg -> toMessage(author, msg)) .flatMapSingle(stub::postMessage) .subscribe( ChatClient::doNothing, throwable -> printLine(console, "ERROR", throwable.getMessage()), done::countDown )); // Wait for a signal to exit, then clean up done.await(); disposables.dispose(); channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); console.getTerminal().restore(); }
Example 18
Source File: AndroidChannelBuilderTest.java From grpc-java with Apache License 2.0 | 4 votes |
@Test @Config(sdk = 23) public void resetConnectBackoff_api23() { TestChannel delegateChannel = new TestChannel(); ManagedChannel androidChannel = new AndroidChannelBuilder.AndroidChannel( delegateChannel, ApplicationProvider.getApplicationContext()); assertThat(delegateChannel.resetCount).isEqualTo(0); // On API levels < 24, the broadcast receiver will invoke resetConnectBackoff() on the first // connectivity action broadcast regardless of previous connection status shadowOf(connectivityManager).setActiveNetworkInfo(WIFI_CONNECTED); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(1); // The broadcast receiver may fire when the active network status has not actually changed ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(1); // Drop the connection shadowOf(connectivityManager).setActiveNetworkInfo(null); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(1); // Notify that a new but not connected network is available shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_DISCONNECTED); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(1); // Establish a connection shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(2); // Disconnect, then shutdown the channel and verify that the broadcast receiver has been // unregistered shadowOf(connectivityManager).setActiveNetworkInfo(null); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); androidChannel.shutdown(); shadowOf(connectivityManager).setActiveNetworkInfo(MOBILE_CONNECTED); ApplicationProvider .getApplicationContext() .sendBroadcast(new Intent(ConnectivityManager.CONNECTIVITY_ACTION)); assertThat(delegateChannel.resetCount).isEqualTo(2); // enterIdle is not called on API levels < 24 assertThat(delegateChannel.enterIdleCount).isEqualTo(0); }
Example 19
Source File: Extract.java From bazel-buildfarm with Apache License 2.0 | 4 votes |
public static void main(String[] args) throws Exception { String host = args[0]; String instanceName = args[1]; Scanner scanner = new Scanner(System.in); ImmutableSet.Builder<Digest> actionDigests = ImmutableSet.builder(); while (scanner.hasNext()) { actionDigests.add(DigestUtil.parseDigest(scanner.nextLine())); } ManagedChannel channel = createChannel(host); Path root = Paths.get("blobs"); downloadActionContents(root, instanceName, actionDigests.build(), channel); channel.shutdown(); }
Example 20
Source File: ChannelFactoryTest.java From pinpoint with Apache License 2.0 | 4 votes |
@Test public void build() throws InterruptedException { HeaderFactory headerFactory = new AgentHeaderFactory("agentId", "appName", System.currentTimeMillis()); CountRecordClientInterceptor countRecordClientInterceptor = new CountRecordClientInterceptor(); ChannelFactoryBuilder channelFactoryBuilder = new DefaultChannelFactoryBuilder(this.getClass().getSimpleName()); channelFactoryBuilder.setHeaderFactory(headerFactory); channelFactoryBuilder.setNameResolverProvider(nameResolverProvider); channelFactoryBuilder.addClientInterceptor(countRecordClientInterceptor); channelFactoryBuilder.setClientOption(new ClientOption.Builder().build()); ChannelFactory channelFactory = channelFactoryBuilder.build(); ManagedChannel managedChannel = channelFactory.build("127.0.0.1", PORT); managedChannel.getState(false); SpanGrpc.SpanStub spanStub = SpanGrpc.newStub(managedChannel); final QueueingStreamObserver<Empty> responseObserver = new QueueingStreamObserver<Empty>(); logger.debug("sendSpan"); StreamObserver<PSpanMessage> sendSpan = spanStub.sendSpan(responseObserver); PSpan pSpan = newSpan(); PSpanMessage message = PSpanMessage.newBuilder().setSpan(pSpan).build(); logger.debug("client-onNext"); sendSpan.onNext(message); logger.debug("wait for response"); Empty value = responseObserver.getValue(); logger.debug("response:{}", value); logger.debug("client-onCompleted"); sendSpan.onCompleted(); Assert.assertTrue(countRecordClientInterceptor.getExecutedInterceptCallCount() == 1); logger.debug("state:{}", managedChannel.getState(true)); spanService.awaitOnCompleted(); logger.debug("managedChannel shutdown"); managedChannel.shutdown(); managedChannel.awaitTermination(1000, TimeUnit.MILLISECONDS); channelFactory.close(); }