io.grpc.stub.ClientCalls#blockingUnaryCall ( )源码实例Demo

下面列出了io.grpc.stub.ClientCalls#blockingUnaryCall ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Test
public void requestWithNoCacheOptionSkipsCache() {
  HelloReply reply1 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
  HelloReply reply2 =
      ClientCalls.blockingUnaryCall(
          channelToUse,
          safeGreeterSayHelloMethod,
          CallOptions.DEFAULT.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true),
          message);
  HelloReply reply3 =
      ClientCalls.blockingUnaryCall(
          channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);

  assertNotEquals(reply1, reply2);
  assertSame(reply1, reply3);
}
 
@Test
public void requestWithNoCacheAndOnlyIfCached_fails() {
  try {
    ClientCalls.blockingUnaryCall(
        channelToUse,
        safeGreeterSayHelloMethod,
        CallOptions.DEFAULT
            .withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true)
            .withOption(SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true),
        message);
    fail("Expected call to fail");
  } catch (StatusRuntimeException sre) {
    assertEquals(Status.UNAVAILABLE.getCode(), sre.getStatus().getCode());
    assertEquals(
        "Unsatisfiable Request (no-cache and only-if-cached conflict)",
        sre.getStatus().getDescription());
  }
}
 
@Test
public void responseNoCacheDirective_notCached() throws Exception {
  cacheControlDirectives.add("no-cache");

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

  assertNotEquals(reply1, reply2);
  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
源代码4 项目: pampas   文件: ClientDynamic.java
public static <ReqT, RespT> void autoCall() throws Exception {
        DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(toUrl("/home/darrenfu/IdeaProjects/pampas/pampas-grpc/df/open/grpc/hello/grpc-test-229014610914606914.jar"));
        Class grpc = loader.load("df.open.grpc.hello.HelloServiceGrpc");
        Class proto = loader.load("df.open.grpc.hello.HelloServiceProto");
        Method getSayHelloMethod = grpc.getDeclaredMethod("getSayHelloMethod");
        MethodDescriptor<ReqT, RespT> methodDescriptor = (MethodDescriptor) getSayHelloMethod.invoke(grpc);

        ClientCall<ReqT, RespT> call =
                new ForwardingClientCall.SimpleForwardingClientCall(channel.newCall(methodDescriptor, callOption.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS))) {

                    public void start(Listener responseListener, Metadata headers) {
                        System.out.println("start call......");
                        super.start(responseListener, headers);
                    }
                };
//        ClientCalls.asyncUnaryCall(call, (ReqT) req.newInstance(), responseFuture);
        Class<?> reqClz = Class.forName("df.open.grpc.hello.HelloServiceProto$HelloReq", false, loader);
        Constructor<?> constructor = reqClz.getDeclaredConstructor();
        constructor.setAccessible(true);
        System.out.println(constructor.isAccessible());

        RespT respT = ClientCalls.blockingUnaryCall(call, (ReqT) constructor.newInstance());
        System.out.println(respT);
        System.out.println("XXXXXXXxx");

    }
 
@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));
}
 
@Test
public void releaseOnError() {
    // Setup server
    startServer((req, observer) -> {
        observer.onError(Status.INVALID_ARGUMENT.asRuntimeException());
    });

    try {
        ClientCalls.blockingUnaryCall(channel, METHOD_DESCRIPTOR, CallOptions.DEFAULT, "foo");
        Assert.fail("Should have failed with UNKNOWN error");
    } catch (StatusRuntimeException e) {
        Assert.assertEquals(Status.Code.INVALID_ARGUMENT, e.getStatus().getCode());
    }
    // Verify
    Mockito.verify(limiter, Mockito.times(1)).acquire(Mockito.isA(GrpcServerRequestContext.class));

    verifyCounts(0, 0, 1, 0);
}
 
@Test
public void combinedResponseCacheControlDirectives_parsesWithoutError() throws Exception {
  cacheControlDirectives.add("max-age=1,no-store , no-cache");

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

  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
@Test
public void responseNoCache_caseInsensitive() throws Exception {
  cacheControlDirectives.add("No-CaCHe");

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

  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
@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);
}
 
源代码10 项目: grpc-java   文件: InProcessTransportTest.java
@Test
public void causeShouldBePropagatedWithStatus() throws Exception {
  server = null;
  String failingServerName = "server_foo";
  String serviceFoo = "service_foo";
  final Status s = Status.INTERNAL.withCause(new Throwable("failing server exception"));
  ServerServiceDefinition definition = ServerServiceDefinition.builder(serviceFoo)
      .addMethod(TestMethodDescriptors.voidMethod(), new ServerCallHandler<Void, Void>() {
        @Override
        public ServerCall.Listener<Void> startCall(
            ServerCall<Void, Void> call, Metadata headers) {
          call.close(s, new Metadata());
          return new ServerCall.Listener<Void>() {};
        }
      })
      .build();
  Server failingServer = InProcessServerBuilder
      .forName(failingServerName)
      .addService(definition)
      .directExecutor()
      .build()
      .start();
  grpcCleanupRule.register(failingServer);
  ManagedChannel channel = InProcessChannelBuilder
      .forName(failingServerName)
      .propagateCauseWithStatus(true)
      .build();
  grpcCleanupRule.register(channel);
  try {
    ClientCalls.blockingUnaryCall(channel, TestMethodDescriptors.voidMethod(),
        CallOptions.DEFAULT, null);
    fail("exception should have been thrown");
  } catch (StatusRuntimeException e) {
    // When propagateCauseWithStatus is true, the cause should be sent forward
    assertEquals(s.getCause(), e.getCause());
  }
}
 
@Test
public void responseNoStoreDirective_notCached() throws Exception {
  cacheControlDirectives.add("no-store");

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

  assertNotEquals(reply1, reply2);
  Truth.assertThat(cache.internalCache).isEmpty();
  Truth.assertThat(cache.removedKeys).isEmpty();
}
 
@SuppressWarnings("unchecked")
@Override
public Object invoke(Object proxy, Method method, Object[] args) {
    String methodName = method.getName();
    String className = method.getDeclaringClass().getName();
    if ("toString".equals(methodName) && args.length == 0) {
        return className + "@" + invoker.hashCode();
    } else if ("hashCode".equals(methodName) && args.length == 0) {
        return invoker.hashCode();
    } else if ("equals".equals(methodName) && args.length == 1) {
        Object another = Utils.safeElement(args, 0);
        return proxy == another;
    }
    String annotationMethodName = method.getAnnotation(GRpcMethod.class).value();
    MethodCallProperty methodCallProperty = callDefinitions.get(StringUtils.isEmpty(annotationMethodName) ? methodName : annotationMethodName);
    ClientCall<Object, Object> clientCall = buildCall(methodCallProperty);
    switch (methodCallProperty.getMethodType()) {
        case UNARY:
            if (method.getReturnType() == ListenableFuture.class) { //等于ClientCalls.futureUnaryCall()
                return ClientCalls.futureUnaryCall(clientCall, Utils.safeElement(args, 0));
            } else if (method.getReturnType().getName().equals("void")) { //等于ClientCalls.asyncUnaryCall();
                if (Utils.checkMethodHasParamClass(method, StreamObserver.class)) {
                    ClientCalls.asyncUnaryCall(clientCall, Utils.safeElement(args, 0), (StreamObserver<Object>) Utils.safeElement(args, 1));
                    return null;
                } else {
                    ClientCalls.blockingUnaryCall(clientCall, Utils.safeElement(args, 0));
                    return null;
                }
            }
            return ClientCalls.blockingUnaryCall(clientCall, Utils.safeElement(args, 0));
        case BIDI_STREAMING://双向流,相当于asyncBidiStreamingCall
            //获取返回类型的泛型
            return ClientCalls.asyncBidiStreamingCall(clientCall, (StreamObserver<Object>) Utils.safeElement(args, 0));
        case CLIENT_STREAMING: //客户端流。等于ClientCalls.asyncClientStreamingCall()
            return ClientCalls.asyncClientStreamingCall(clientCall, (StreamObserver<Object>) Utils.safeElement(args, 0));
        case SERVER_STREAMING://等于ClientCalls.blockingServerStreamingCall
            return ClientCalls.blockingServerStreamingCall(clientCall, Utils.safeElement(args, 0));
    }
    return null;
}
 
@Test
public void responseMustRevalidateDirective_isIgnored() throws Exception {
  cacheControlDirectives.add("must-revalidate");

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

  assertSame(reply1, reply2);
}
 
@Test
public void responseMustRevalidateDirective_isIgnored() throws Exception {
  cacheControlDirectives.add("must-revalidate");

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

  assertSame(reply1, reply2);
}
 
源代码15 项目: grpc-nebula-java   文件: AbstractInteropTest.java
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */
public void cacheableUnary() {
  // Set safe to true.
  MethodDescriptor<SimpleRequest, SimpleResponse> safeCacheableUnaryCallMethod =
      TestServiceGrpc.getCacheableUnaryCallMethod().toBuilder().setSafe(true).build();
  // Set fake user IP since some proxies (GFE) won't cache requests from localhost.
  Metadata.Key<String> userIpKey = Metadata.Key.of("x-user-ip", Metadata.ASCII_STRING_MARSHALLER);
  Metadata metadata = new Metadata();
  metadata.put(userIpKey, "1.2.3.4");
  Channel channelWithUserIpKey =
      ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata));
  SimpleRequest requests1And2 =
      SimpleRequest.newBuilder()
          .setPayload(
              Payload.newBuilder()
                  .setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
          .build();
  SimpleRequest request3 =
      SimpleRequest.newBuilder()
          .setPayload(
              Payload.newBuilder()
                  .setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
          .build();

  SimpleResponse response1 =
      ClientCalls.blockingUnaryCall(
          channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
  SimpleResponse response2 =
      ClientCalls.blockingUnaryCall(
          channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
  SimpleResponse response3 =
      ClientCalls.blockingUnaryCall(
          channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, request3);

  assertEquals(response1, response2);
  assertNotEquals(response1, response3);
}
 
@Test
public void differentServiceCallsAreNotConflated() {
  MethodDescriptor<HelloRequest, HelloReply> anotherSafeMethod =
      AnotherGreeterGrpc.getSayHelloMethod().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);
}
 
@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));
}
 
@Test
public void noTrailerReportIfNoRecordedMetrics() {
  ClientCalls.blockingUnaryCall(channelToUse, SIMPLE_METHOD, CallOptions.DEFAULT, REQUEST);
  Metadata receivedTrailers = trailersCapture.get();
  assertThat(
      receivedTrailers.get(OrcaMetricReportingServerInterceptor.ORCA_ENDPOINT_LOAD_METRICS_KEY))
      .isNull();
}
 
@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().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);
  }
}
 
源代码20 项目: 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().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);
  }
}