Java 类io.grpc.examples.helloworld.GreeterGrpc 实例源码

项目: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(true).build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
项目:grpc-java    文件:ErrorHandlingClient.java   
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Narwhal"));
      // Cause is not transmitted over the wire.
      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().setName("Marge").build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目: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(true).build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
项目:grpc-java    文件:HeaderClientInterceptorTest.java   
@Test
public void clientHeaderDeliveredToServer() {
  grpcServerRule.getServiceRegistry()
      .addService(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor));
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
      ClientInterceptors.intercept(grpcServerRule.getChannel(), new HeaderClientInterceptor()));
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);

  try {
    blockingStub.sayHello(HelloRequest.getDefaultInstance());
    fail();
  } catch (StatusRuntimeException expected) {
    // expected because the method is not implemented at server side
  }

  verify(mockServerInterceptor).interceptCall(
      Matchers.<ServerCall<HelloRequest, HelloReply>>any(),
      metadataCaptor.capture(),
      Matchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
  assertEquals(
      "customRequestValue",
      metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
项目:grpc-java    文件:HelloworldActivity.java   
@Override
protected String doInBackground(String... params) {
  String host = params[0];
  String message = params[1];
  String portStr = params[2];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply = stub.sayHello(request);
    return reply.getMessage();
  } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}
项目:grpc-java    文件:SafeMethodCachingInterceptorTest.java   
@Test
public void afterResponseMaxAge_cacheEntryInvalidated() throws Exception {
  cacheControlDirectives.add("max-age=1");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  assertSame(reply1, reply2);

  // Wait for cache entry to expire
  sleepAtLeast(1001);

  assertNotEquals(
      reply1,
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
  Truth.assertThat(cache.removedKeys).hasSize(1);
  assertEquals(
      new SafeMethodCachingInterceptor.Key(
          GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
      cache.removedKeys.get(0));
}
项目:book_ldrtc    文件:CompressingHelloWorldClient.java   
/** Say hello to server. */
public void greet(final String name) {
  final ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.METHOD_SAY_HELLO, CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new Listener<HelloReply>() {
    @Override
    public void onHeaders(Metadata headers) {
      super.onHeaders(headers);
      String encoding = headers.get(GrpcUtil.MESSAGE_ENCODING_KEY);
      if (encoding == null) {
        throw new RuntimeException("No compression selected!");
      }
    }

    @Override
    public void onMessage(HelloReply message) {
      super.onMessage(message);
      logger.info("Greeting: " + message.getMessage());
      latch.countDown();
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      latch.countDown();
      if (!status.isOk()) {
        throw status.asRuntimeException();
      }
    }
  }, new Metadata());

  call.setMessageCompression(true);
  call.sendMessage(HelloRequest.newBuilder().setName(name).build());
  call.request(1);
  call.halfClose();

  Uninterruptibles.awaitUninterruptibly(latch, 100, TimeUnit.SECONDS);
}
项目:book_ldrtc    文件:CustomHeaderClient.java   
/**
 * A custom client.
 */
private CustomHeaderClient(String host, int port) {
  originChannel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext(true)
      .build();
  ClientInterceptor interceptor = new HeaderClientInterceptor();
  Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
项目:grpc-java    文件:CompressingHelloWorldClient.java   
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public CompressingHelloWorldClient(String host, int port) {
  channel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext(true)
      .build();
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
项目:grpc-java    文件:CustomHeaderClient.java   
/**
 * A custom client.
 */
private CustomHeaderClient(String host, int port) {
  originChannel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext(true)
      .build();
  ClientInterceptor interceptor = new HeaderClientInterceptor();
  Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
项目:grpc-java    文件:HelloJsonServer.java   
@Override
public ServerServiceDefinition bindService() {
  return io.grpc.ServerServiceDefinition
      .builder(GreeterGrpc.getServiceDescriptor().getName())
      .addMethod(HelloJsonClient.HelloJsonStub.METHOD_SAY_HELLO,
          asyncUnaryCall(
              new UnaryMethod<HelloRequest, HelloReply>() {
                @Override
                public void invoke(
                    HelloRequest request, StreamObserver<HelloReply> responseObserver) {
                  sayHello(request, responseObserver);
                }
              }))
      .build();
}
项目:grpc-java    文件:ErrorHandlingClient.java   
void blockingCall() {
  GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
  try {
    stub.sayHello(HelloRequest.newBuilder().setName("Bart").build());
  } catch (Exception e) {
    Status status = Status.fromThrowable(e);
    Verify.verify(status.getCode() == Status.Code.INTERNAL);
    Verify.verify(status.getDescription().contains("Eggplant"));
    // Cause is not transmitted over the wire.
  }
}
项目:grpc-java    文件:ErrorHandlingClient.java   
void futureCallCallback() {
  GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
  ListenableFuture<HelloReply> response =
      stub.sayHello(HelloRequest.newBuilder().setName("Maggie").build());

  final CountDownLatch latch = new CountDownLatch(1);

  Futures.addCallback(
      response,
      new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(@Nullable HelloReply result) {
          // Won't be called, since the server in this example always fails.
        }

        @Override
        public void onFailure(Throwable t) {
          Status status = Status.fromThrowable(t);
          Verify.verify(status.getCode() == Status.Code.INTERNAL);
          Verify.verify(status.getDescription().contains("Crybaby"));
          // Cause is not transmitted over the wire..
          latch.countDown();
        }
      },
      directExecutor());

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目:grpc-java    文件:ErrorHandlingClient.java   
void asyncCall() {
  GreeterStub stub = GreeterGrpc.newStub(channel);
  HelloRequest request = HelloRequest.newBuilder().setName("Homer").build();
  final CountDownLatch latch = new CountDownLatch(1);
  StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {

    @Override
    public void onNext(HelloReply value) {
      // Won't be called.
    }

    @Override
    public void onError(Throwable t) {
      Status status = Status.fromThrowable(t);
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(status.getDescription().contains("Overbite"));
      // Cause is not transmitted over the wire..
      latch.countDown();
    }

    @Override
    public void onCompleted() {
      // Won't be called, since the server in this example always fails.
    }
  };
  stub.sayHello(request, responseObserver);

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目:grpc-java    文件:DetailErrorSample.java   
void blockingCall() {
  GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
  try {
    stub.sayHello(HelloRequest.newBuilder().build());
  } catch (Exception e) {
    verifyErrorReply(e);
  }
}
项目:grpc-java    文件:DetailErrorSample.java   
void futureCallCallback() {
  GreeterFutureStub stub = GreeterGrpc.newFutureStub(channel);
  ListenableFuture<HelloReply> response =
      stub.sayHello(HelloRequest.newBuilder().build());

  final CountDownLatch latch = new CountDownLatch(1);

  Futures.addCallback(
      response,
      new FutureCallback<HelloReply>() {
        @Override
        public void onSuccess(@Nullable HelloReply result) {
          // Won't be called, since the server in this example always fails.
        }

        @Override
        public void onFailure(Throwable t) {
          verifyErrorReply(t);
          latch.countDown();
        }
      },
      directExecutor());

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目:grpc-java    文件:DetailErrorSample.java   
void asyncCall() {
  GreeterStub stub = GreeterGrpc.newStub(channel);
  HelloRequest request = HelloRequest.newBuilder().build();
  final CountDownLatch latch = new CountDownLatch(1);
  StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {

    @Override
    public void onNext(HelloReply value) {
      // Won't be called.
    }

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

    @Override
    public void onCompleted() {
      // Won't be called, since the server in this example always fails.
    }
  };
  stub.sayHello(request, responseObserver);

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目:grpc-java    文件:DetailErrorSample.java   
/**
 * This is more advanced and does not make use of the stub.  You should not normally need to do
 * this, but here is how you would.
 */
void advancedAsyncCall() {
  ClientCall<HelloRequest, HelloReply> call =
      channel.newCall(GreeterGrpc.getSayHelloMethod(), CallOptions.DEFAULT);

  final CountDownLatch latch = new CountDownLatch(1);

  call.start(new ClientCall.Listener<HelloReply>() {

    @Override
    public void onClose(Status status, Metadata trailers) {
      Verify.verify(status.getCode() == Status.Code.INTERNAL);
      Verify.verify(trailers.containsKey(DEBUG_INFO_TRAILER_KEY));
      try {
        Verify.verify(trailers.get(DEBUG_INFO_TRAILER_KEY).equals(DEBUG_INFO));
      } catch (IllegalArgumentException e) {
        throw new VerifyException(e);
      }

      latch.countDown();
    }
  }, new Metadata());

  call.sendMessage(HelloRequest.newBuilder().build());
  call.halfClose();

  if (!Uninterruptibles.awaitUninterruptibly(latch, 1, TimeUnit.SECONDS)) {
    throw new RuntimeException("timeout!");
  }
}
项目:grpc-java    文件:HeaderServerInterceptorTest.java   
@Test
public void serverHeaderDeliveredToClient() {
  class SpyingClientInterceptor implements ClientInterceptor {
    ClientCall.Listener<?> spyListener;

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
      return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
        @Override
        public void start(Listener<RespT> responseListener, Metadata headers) {
          spyListener = responseListener =
              mock(ClientCall.Listener.class, delegatesTo(responseListener));
          super.start(responseListener, headers);
        }
      };
    }
  }

  SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
  GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(grpcServerRule.getChannel())
      .withInterceptors(clientInterceptor);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);

  blockingStub.sayHello(HelloRequest.getDefaultInstance());

  assertNotNull(clientInterceptor.spyListener);
  verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
  assertEquals(
      "customRespondValue",
      metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
项目:grpc-java    文件:SafeMethodCachingInterceptorTest.java   
@Test
public void invalidResponseMaxAge_usesDefault() throws Exception {
  SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
      SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
  channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
  cacheControlDirectives.add("max-age=-10");

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  assertEquals(reply1, reply2);

  // Wait for cache entry to expire
  sleepAtLeast(1001);

  assertNotEquals(
      reply1,
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
  Truth.assertThat(cache.removedKeys).hasSize(1);
  assertEquals(
      new SafeMethodCachingInterceptor.Key(
          GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
      cache.removedKeys.get(0));
}
项目:grpc-java    文件:SafeMethodCachingInterceptorTest.java   
@Test
public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception {
  SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
      SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
  channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  assertSame(reply1, reply2);

  // Wait for cache entry to expire
  sleepAtLeast(1001);

  assertNotEquals(
      reply1,
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
  Truth.assertThat(cache.removedKeys).hasSize(1);
  assertEquals(
      new SafeMethodCachingInterceptor.Key(
          GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
      cache.removedKeys.get(0));
}
项目:grpc-java    文件:SafeMethodCachingInterceptorTest.java   
@Test
public void unsafeCallsAreNotCached() {
  GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse);

  HelloReply reply1 = stub.sayHello(message);
  HelloReply reply2 = stub.sayHello(message);

  assertNotEquals(reply1, reply2);
}
项目:grpc-java    文件:SafeMethodCachingInterceptorTest.java   
@Test
public void differentMethodCallsAreNotConflated() {
  MethodDescriptor<HelloRequest, HelloReply> anotherSafeMethod =
      GreeterGrpc.getSayAnotherHelloMethod().toBuilder().setSafe(true).build();

  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse, anotherSafeMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
}
项目:spring-boot-grpc-example    文件:GrpcClientService.java   
public String sendMessage(String name) {
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverChannel);
    HelloReply response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());
    return response.getMessage();
}
项目:spring-boot-grpc-example    文件:GrpcClientService.java   
public String sendMessage(String name) {
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverChannel);
    HelloReply response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());
    return response.getMessage();
}
项目:rejoiner    文件:HelloWorldSchemaModule.java   
@Query("sayHello")
HelloReply sayHello(HelloRequest request, GreeterGrpc.GreeterBlockingStub client) {
  return client.sayHello(request);
}
项目:rejoiner    文件:HelloWorldClientModule.java   
@Override
protected void configure() {
  ManagedChannel channel =
      ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build();
  bind(GreeterGrpc.GreeterBlockingStub.class).toInstance(GreeterGrpc.newBlockingStub(channel));
}
项目:grpc-java    文件:ClientCacheExampleActivity.java   
@Override
protected String doInBackground(Object... params) {
  String host = (String) params[0];
  String message = (String) params[1];
  String portStr = (String) params[2];
  boolean useGet = (boolean) params[3];
  boolean noCache = (boolean) params[4];
  boolean onlyIfCached = (boolean) params[5];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
    Channel channelToUse =
        ClientInterceptors.intercept(
            channel, SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache));
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply;
    if (useGet) {
      MethodDescriptor<HelloRequest, HelloReply> safeCacheableUnaryCallMethod =
          GreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build();
      CallOptions callOptions = CallOptions.DEFAULT;
      if (noCache) {
        callOptions =
            callOptions.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true);
      }
      if (onlyIfCached) {
        callOptions =
            callOptions.withOption(
                SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true);
      }
      reply =
          ClientCalls.blockingUnaryCall(
              channelToUse, safeCacheableUnaryCallMethod, callOptions, request);
    } else {
      GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse);
      reply = stub.sayHello(request);
    }
    return reply.getMessage();
  } catch (Exception e) {
    Log.e(TAG, "RPC failed", e);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}