当前位置: 首页>>代码示例>>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;未经允许,请勿转载。