當前位置: 首頁>>代碼示例>>Java>>正文


Java Server.shutdownNow方法代碼示例

本文整理匯總了Java中io.grpc.Server.shutdownNow方法的典型用法代碼示例。如果您正苦於以下問題:Java Server.shutdownNow方法的具體用法?Java Server.shutdownNow怎麽用?Java Server.shutdownNow使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.grpc.Server的用法示例。


在下文中一共展示了Server.shutdownNow方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: close

import io.grpc.Server; //導入方法依賴的package包/類
/**
 * 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;
        }
    }
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:21,代碼來源:GrpcServerHost.java

示例2: shutdownGracefully

import io.grpc.Server; //導入方法依賴的package包/類
/**
 * Attempt to {@link Server#shutdown()} the {@link Server} gracefully. If the max wait time is exceeded, give up and
 * perform a hard {@link Server#shutdownNow()}.
 *
 * @param server the server to be shutdown
 * @param timeout the max amount of time to wait for graceful shutdown to occur
 * @param unit the time unit denominating the shutdown timeout
 * @return the given server
 * @throws InterruptedException if waiting for termination is interrupted
 */
public static Server shutdownGracefully(Server server, long timeout, TimeUnit unit) throws InterruptedException {
    Preconditions.checkNotNull(server, "server");
    Preconditions.checkArgument(timeout > 0, "timeout must be greater than 0");
    Preconditions.checkNotNull(unit, "unit");

    server.shutdown();

    try {
        server.awaitTermination(timeout, unit);
    } finally {
        server.shutdownNow();
    }

    return server;
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:26,代碼來源:Servers.java

示例3: serverRunsAndRespondsCorrectly

import io.grpc.Server; //導入方法依賴的package包/類
@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();
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:32,代碼來源:CompletableFutureEndToEndTest.java

示例4: killServerReceivedMessage

import io.grpc.Server; //導入方法依賴的package包/類
private int killServerReceivedMessage() {
  for (int port : eventsMap.keySet()) {
    if (!eventsMap.get(port).isEmpty()) {
      Server serverToKill = servers.get(port);
      serverToKill.shutdownNow();
      return port;
    }
  }
  throw new IllegalStateException("None of the servers received any message");
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-saga,代碼行數:11,代碼來源:LoadBalancedClusterMessageSenderTest.java

示例5: testKeepAlive

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testKeepAlive() throws IOException, ExecutionException, InterruptedException {

    // Verify that keep-alive timeout less than permissible by the server results in a failure.
    final ControllerImpl controller = new ControllerImpl(NettyChannelBuilder.forAddress("localhost", serverPort)
            .keepAliveTime(10, TimeUnit.SECONDS).usePlaintext(true),
            ControllerImplConfig.builder().retryAttempts(1).build(), this.executor);
    CompletableFuture<Boolean> createStreamStatus = controller.createStream(StreamConfiguration.builder()
            .streamName("streamdelayed")
            .scope("scope1")
            .scalingPolicy(ScalingPolicy.fixed(1))
            .build());
    AssertExtensions.assertThrows("Should throw RetriesExhaustedException", createStreamStatus,
            throwable -> throwable instanceof RetriesExhaustedException);

    // Verify that the same RPC with permissible keepalive time succeeds.
    int serverPort2 = TestUtils.getAvailableListenPort();
    Server testServer = NettyServerBuilder.forPort(serverPort2)
            .addService(testServerImpl)
            .permitKeepAliveTime(5, TimeUnit.SECONDS)
            .build()
            .start();
    final ControllerImpl controller1 = new ControllerImpl(NettyChannelBuilder.forAddress("localhost", serverPort2)
            .keepAliveTime(10, TimeUnit.SECONDS).usePlaintext(true),
            ControllerImplConfig.builder().retryAttempts(1).build(), this.executor);
    createStreamStatus = controller1.createStream(StreamConfiguration.builder()
            .streamName("streamdelayed")
            .scope("scope1")
            .scalingPolicy(ScalingPolicy.fixed(1))
            .build());
    assertTrue(createStreamStatus.get());
    testServer.shutdownNow();
}
 
開發者ID:pravega,項目名稱:pravega,代碼行數:34,代碼來源:ControllerImplTest.java

示例6: shutdown

import io.grpc.Server; //導入方法依賴的package包/類
private static void shutdown(Server server) throws InterruptedException {
    // TODO shutdownNow() has been needed to interrupt grpc threads since grpc-java 1.7.0
    server.shutdownNow();
    if (!server.awaitTermination(10, SECONDS)) {
        throw new IllegalStateException("Timed out waiting for grpc server to terminate");
    }
}
 
開發者ID:glowroot,項目名稱:glowroot,代碼行數:8,代碼來源:GrpcServer.java

示例7: testLogging

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testLogging() throws Exception {
  AtomicBoolean clientClosedStream = new AtomicBoolean();
  Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
  AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver =
      new AtomicReference<>();
  CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver =
      TestStreams.withOnNext(
          (BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList()))
      .withOnCompleted(new Runnable() {
        @Override
        public void run() {
          // Remember that the client told us that this stream completed
          clientClosedStream.set(true);
          outboundServerObserver.get().onCompleted();
        }
      }).build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
          .addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {
            @Override
            public StreamObserver<BeamFnApi.LogEntry.List> logging(
                StreamObserver<BeamFnApi.LogControl> outboundObserver) {
              outboundServerObserver.set(outboundObserver);
              return inboundServerObserver;
            }
          })
          .build();
  server.start();

  ManagedChannel channel =
      InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
  try {

    BeamFnLoggingClient client = new BeamFnLoggingClient(
        PipelineOptionsFactory.fromArgs(new String[] {
            "--defaultSdkHarnessLogLevel=OFF",
            "--sdkHarnessLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}"
        }).create(),
        apiServiceDescriptor,
        (Endpoints.ApiServiceDescriptor descriptor) -> channel);

    // Ensure that log levels were correctly set.
    assertEquals(Level.OFF,
        LogManager.getLogManager().getLogger("").getLevel());
    assertEquals(Level.FINE,
        LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());

    // Should be filtered because the default log level override is OFF
    LogManager.getLogManager().getLogger("").log(FILTERED_RECORD);
    // Should not be filtered because the default log level override for ConfiguredLogger is DEBUG
    LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD);
    LogManager.getLogManager().getLogger("ConfiguredLogger").log(TEST_RECORD_WITH_EXCEPTION);
    client.close();

    // Verify that after close, log levels are reset.
    assertEquals(Level.INFO, LogManager.getLogManager().getLogger("").getLevel());
    assertNull(LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());

    assertTrue(clientClosedStream.get());
    assertTrue(channel.isShutdown());
    assertThat(values, contains(TEST_ENTRY, TEST_ENTRY_WITH_EXCEPTION));
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:71,代碼來源:BeamFnLoggingClientTest.java

示例8: testWhenServerFailsThatClientIsAbleToCleanup

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testWhenServerFailsThatClientIsAbleToCleanup() throws Exception {
  AtomicBoolean clientClosedStream = new AtomicBoolean();
  Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
  AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver =
      new AtomicReference<>();
  CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver = TestStreams.withOnNext(
      (BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList()))
      .build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
      .addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {
        @Override
        public StreamObserver<BeamFnApi.LogEntry.List> logging(
            StreamObserver<BeamFnApi.LogControl> outboundObserver) {
          outboundServerObserver.set(outboundObserver);
          outboundObserver.onError(Status.INTERNAL.withDescription("TEST ERROR").asException());
          return inboundServerObserver;
        }
      })
      .build();
  server.start();

  ManagedChannel channel =
      InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
  try {
    BeamFnLoggingClient client = new BeamFnLoggingClient(
        PipelineOptionsFactory.fromArgs(new String[] {
            "--defaultSdkHarnessLogLevel=OFF",
            "--sdkHarnessLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}"
        }).create(),
        apiServiceDescriptor,
        (Endpoints.ApiServiceDescriptor descriptor) -> channel);

    thrown.expectMessage("TEST ERROR");
    client.close();
  } finally {
    // Verify that after close, log levels are reset.
    assertEquals(Level.INFO, LogManager.getLogManager().getLogger("").getLevel());
    assertNull(LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());

    assertTrue(channel.isShutdown());

    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:51,代碼來源:BeamFnLoggingClientTest.java

示例9: testWhenServerHangsUpEarlyThatClientIsAbleCleanup

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testWhenServerHangsUpEarlyThatClientIsAbleCleanup() throws Exception {
  AtomicBoolean clientClosedStream = new AtomicBoolean();
  Collection<BeamFnApi.LogEntry> values = new ConcurrentLinkedQueue<>();
  AtomicReference<StreamObserver<BeamFnApi.LogControl>> outboundServerObserver =
      new AtomicReference<>();
  CallStreamObserver<BeamFnApi.LogEntry.List> inboundServerObserver =
      TestStreams.withOnNext(
          (BeamFnApi.LogEntry.List logEntries) -> values.addAll(logEntries.getLogEntriesList()))
          .build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
      .addService(new BeamFnLoggingGrpc.BeamFnLoggingImplBase() {
        @Override
        public StreamObserver<BeamFnApi.LogEntry.List> logging(
            StreamObserver<BeamFnApi.LogControl> outboundObserver) {
          outboundServerObserver.set(outboundObserver);
          outboundObserver.onCompleted();
          return inboundServerObserver;
        }
      })
      .build();
  server.start();

  ManagedChannel channel =
      InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();
  try {
    BeamFnLoggingClient client = new BeamFnLoggingClient(
        PipelineOptionsFactory.fromArgs(new String[] {
            "--defaultSdkHarnessLogLevel=OFF",
            "--sdkHarnessLogLevelOverrides={\"ConfiguredLogger\": \"DEBUG\"}"
        }).create(),
        apiServiceDescriptor,
        (Endpoints.ApiServiceDescriptor descriptor) -> channel);

    client.close();
  } finally {
    // Verify that after close, log levels are reset.
    assertEquals(Level.INFO, LogManager.getLogManager().getLogger("").getLevel());
    assertNull(LogManager.getLogManager().getLogger("ConfiguredLogger").getLevel());

    assertTrue(channel.isShutdown());

    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:51,代碼來源:BeamFnLoggingClientTest.java

示例10: testForInboundConsumer

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testForInboundConsumer() throws Exception {
  CountDownLatch waitForClientToConnect = new CountDownLatch(1);
  Collection<WindowedValue<String>> inboundValuesA = new ConcurrentLinkedQueue<>();
  Collection<WindowedValue<String>> inboundValuesB = new ConcurrentLinkedQueue<>();
  Collection<BeamFnApi.Elements> inboundServerValues = new ConcurrentLinkedQueue<>();
  AtomicReference<StreamObserver<BeamFnApi.Elements>> outboundServerObserver =
      new AtomicReference<>();
  CallStreamObserver<BeamFnApi.Elements> inboundServerObserver =
      TestStreams.withOnNext(inboundServerValues::add).build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
          .addService(new BeamFnDataGrpc.BeamFnDataImplBase() {
            @Override
            public StreamObserver<BeamFnApi.Elements> data(
                StreamObserver<BeamFnApi.Elements> outboundObserver) {
              outboundServerObserver.set(outboundObserver);
              waitForClientToConnect.countDown();
              return inboundServerObserver;
            }
          })
          .build();
  server.start();
  try {
    ManagedChannel channel =
        InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();

  BeamFnDataGrpcClient clientFactory = new BeamFnDataGrpcClient(
      PipelineOptionsFactory.create(),
      (Endpoints.ApiServiceDescriptor descriptor) -> channel,
      this::createStreamForTest);

    CompletableFuture<Void> readFutureA =
        clientFactory.receive(
            apiServiceDescriptor, ENDPOINT_A, CODER, inboundValuesA::add);

    waitForClientToConnect.await();
    outboundServerObserver.get().onNext(ELEMENTS_A_1);
    // Purposefully transmit some data before the consumer for B is bound showing that
    // data is not lost
    outboundServerObserver.get().onNext(ELEMENTS_B_1);
    Thread.sleep(100);

    CompletableFuture<Void> readFutureB =
        clientFactory.receive(
            apiServiceDescriptor, ENDPOINT_B, CODER, inboundValuesB::add);

    // Show that out of order stream completion can occur.
    readFutureB.get();
    assertThat(inboundValuesB, contains(
        valueInGlobalWindow("JKL"), valueInGlobalWindow("MNO")));

    outboundServerObserver.get().onNext(ELEMENTS_A_2);
    readFutureA.get();
    assertThat(inboundValuesA, contains(
        valueInGlobalWindow("ABC"), valueInGlobalWindow("DEF"), valueInGlobalWindow("GHI")));
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:65,代碼來源:BeamFnDataGrpcClientTest.java

示例11: testForInboundConsumerThatThrows

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testForInboundConsumerThatThrows() throws Exception {
  CountDownLatch waitForClientToConnect = new CountDownLatch(1);
  AtomicInteger consumerInvoked = new AtomicInteger();
  Collection<BeamFnApi.Elements> inboundServerValues = new ConcurrentLinkedQueue<>();
  AtomicReference<StreamObserver<BeamFnApi.Elements>> outboundServerObserver =
      new AtomicReference<>();
  CallStreamObserver<BeamFnApi.Elements> inboundServerObserver =
      TestStreams.withOnNext(inboundServerValues::add).build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
          .addService(new BeamFnDataGrpc.BeamFnDataImplBase() {
            @Override
            public StreamObserver<BeamFnApi.Elements> data(
                StreamObserver<BeamFnApi.Elements> outboundObserver) {
              outboundServerObserver.set(outboundObserver);
              waitForClientToConnect.countDown();
              return inboundServerObserver;
            }
          })
          .build();
  server.start();
  RuntimeException exceptionToThrow = new RuntimeException("TestFailure");
  try {
    ManagedChannel channel =
        InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();

    BeamFnDataGrpcClient clientFactory = new BeamFnDataGrpcClient(
        PipelineOptionsFactory.create(),
        (Endpoints.ApiServiceDescriptor descriptor) -> channel,
        this::createStreamForTest);

    CompletableFuture<Void> readFuture =
        clientFactory.receive(
            apiServiceDescriptor,
            ENDPOINT_A,
            CODER,
            t -> {
              consumerInvoked.incrementAndGet();
              throw exceptionToThrow;
            });

    waitForClientToConnect.await();

    // This first message should cause a failure afterwards all other messages are dropped.
    outboundServerObserver.get().onNext(ELEMENTS_A_1);
    outboundServerObserver.get().onNext(ELEMENTS_A_2);

    try {
      readFuture.get();
      fail("Expected channel to fail");
    } catch (ExecutionException e) {
      assertEquals(exceptionToThrow, e.getCause());
    }
    // The server should not have received any values
    assertThat(inboundServerValues, empty());
    // The consumer should have only been invoked once
    assertEquals(1, consumerInvoked.get());
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:67,代碼來源:BeamFnDataGrpcClientTest.java

示例12: testForOutboundConsumer

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void testForOutboundConsumer() throws Exception {
  CountDownLatch waitForInboundServerValuesCompletion = new CountDownLatch(2);
  Collection<BeamFnApi.Elements> inboundServerValues = new ConcurrentLinkedQueue<>();
  CallStreamObserver<BeamFnApi.Elements> inboundServerObserver =
      TestStreams.withOnNext(
          new Consumer<Elements>() {
            @Override
            public void accept(BeamFnApi.Elements t) {
              inboundServerValues.add(t);
              waitForInboundServerValuesCompletion.countDown();
            }
          }
          ).build();

  Endpoints.ApiServiceDescriptor apiServiceDescriptor =
      Endpoints.ApiServiceDescriptor.newBuilder()
          .setUrl(this.getClass().getName() + "-" + UUID.randomUUID().toString())
          .build();
  Server server = InProcessServerBuilder.forName(apiServiceDescriptor.getUrl())
          .addService(new BeamFnDataGrpc.BeamFnDataImplBase() {
            @Override
            public StreamObserver<BeamFnApi.Elements> data(
                StreamObserver<BeamFnApi.Elements> outboundObserver) {
              return inboundServerObserver;
            }
          })
          .build();
  server.start();
  try {
    ManagedChannel channel =
        InProcessChannelBuilder.forName(apiServiceDescriptor.getUrl()).build();

    BeamFnDataGrpcClient clientFactory = new BeamFnDataGrpcClient(
        PipelineOptionsFactory.fromArgs(
            new String[]{ "--experiments=beam_fn_api_data_buffer_limit=20" }).create(),
        (Endpoints.ApiServiceDescriptor descriptor) -> channel,
        this::createStreamForTest);

    try (CloseableFnDataReceiver<WindowedValue<String>> consumer =
        clientFactory.send(apiServiceDescriptor, ENDPOINT_A, CODER)) {
      consumer.accept(valueInGlobalWindow("ABC"));
      consumer.accept(valueInGlobalWindow("DEF"));
      consumer.accept(valueInGlobalWindow("GHI"));
    }

    waitForInboundServerValuesCompletion.await();

    assertThat(inboundServerValues, contains(ELEMENTS_A_1, ELEMENTS_A_2));
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:54,代碼來源:BeamFnDataGrpcClientTest.java

示例13: pullOneMessage

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void pullOneMessage() throws IOException {
  String expectedSubscription = SUBSCRIPTION.getPath();
  final PullRequest expectedRequest =
      PullRequest.newBuilder()
                 .setSubscription(expectedSubscription)
                 .setReturnImmediately(true)
                 .setMaxMessages(10)
                 .build();
  Timestamp timestamp = Timestamp.newBuilder()
                                 .setSeconds(PUB_TIME / 1000)
                                 .setNanos((int) (PUB_TIME % 1000) * 1000)
                                 .build();
  PubsubMessage expectedPubsubMessage =
      PubsubMessage.newBuilder()
                   .setMessageId(MESSAGE_ID)
                   .setData(
                       ByteString.copyFrom(DATA.getBytes()))
                   .setPublishTime(timestamp)
                   .putAllAttributes(ATTRIBUTES)
                   .putAllAttributes(
                       ImmutableMap.of(TIMESTAMP_ATTRIBUTE,
                                       String.valueOf(MESSAGE_TIME),
                           ID_ATTRIBUTE, RECORD_ID))
                   .build();
  ReceivedMessage expectedReceivedMessage =
      ReceivedMessage.newBuilder()
                     .setMessage(expectedPubsubMessage)
                     .setAckId(ACK_ID)
                     .build();
  final PullResponse response =
      PullResponse.newBuilder()
                  .addAllReceivedMessages(ImmutableList.of(expectedReceivedMessage))
                  .build();

  final List<PullRequest> requestsReceived = new ArrayList<>();
  SubscriberImplBase subscriberImplBase = new SubscriberImplBase() {
    @Override
    public void pull(PullRequest request, StreamObserver<PullResponse> responseObserver) {
      requestsReceived.add(request);
      responseObserver.onNext(response);
      responseObserver.onCompleted();
    }
  };
  Server server = InProcessServerBuilder.forName(channelName)
      .addService(subscriberImplBase)
      .build()
      .start();
  try {
    List<IncomingMessage> acutalMessages = client.pull(REQ_TIME, SUBSCRIPTION, 10, true);
    assertEquals(1, acutalMessages.size());
    IncomingMessage actualMessage = acutalMessages.get(0);
    assertEquals(ACK_ID, actualMessage.ackId);
    assertEquals(DATA, new String(actualMessage.elementBytes));
    assertEquals(RECORD_ID, actualMessage.recordId);
    assertEquals(REQ_TIME, actualMessage.requestTimeMsSinceEpoch);
    assertEquals(MESSAGE_TIME, actualMessage.timestampMsSinceEpoch);
    assertEquals(expectedRequest, Iterables.getOnlyElement(requestsReceived));
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:63,代碼來源:PubsubGrpcClientTest.java

示例14: publishOneMessage

import io.grpc.Server; //導入方法依賴的package包/類
@Test
public void publishOneMessage() throws IOException {
  String expectedTopic = TOPIC.getPath();
  PubsubMessage expectedPubsubMessage =
      PubsubMessage.newBuilder()
                   .setData(ByteString.copyFrom(DATA.getBytes()))
                   .putAllAttributes(ATTRIBUTES)
                   .putAllAttributes(
                       ImmutableMap.of(TIMESTAMP_ATTRIBUTE, String.valueOf(MESSAGE_TIME),
                                       ID_ATTRIBUTE, RECORD_ID))
                   .build();
  final PublishRequest expectedRequest =
      PublishRequest.newBuilder()
                    .setTopic(expectedTopic)
                    .addAllMessages(
                        ImmutableList.of(expectedPubsubMessage))
                    .build();
  final PublishResponse response =
      PublishResponse.newBuilder()
                     .addAllMessageIds(ImmutableList.of(MESSAGE_ID))
                     .build();

  final List<PublishRequest> requestsReceived = new ArrayList<>();
  PublisherImplBase publisherImplBase = new PublisherImplBase() {
    @Override
    public void publish(
        PublishRequest request, StreamObserver<PublishResponse> responseObserver) {
      requestsReceived.add(request);
      responseObserver.onNext(response);
      responseObserver.onCompleted();
    }
  };
  Server server = InProcessServerBuilder.forName(channelName)
      .addService(publisherImplBase)
      .build()
      .start();
  try {
    OutgoingMessage actualMessage = new OutgoingMessage(
            DATA.getBytes(), ATTRIBUTES, MESSAGE_TIME, RECORD_ID);
    int n = client.publish(TOPIC, ImmutableList.of(actualMessage));
    assertEquals(1, n);
    assertEquals(expectedRequest, Iterables.getOnlyElement(requestsReceived));
  } finally {
    server.shutdownNow();
  }
}
 
開發者ID:apache,項目名稱:beam,代碼行數:47,代碼來源:PubsubGrpcClientTest.java


注:本文中的io.grpc.Server.shutdownNow方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。