Java Code Examples for io.grpc.stub.ClientCalls#asyncUnaryCall()

The following examples show how to use io.grpc.stub.ClientCalls#asyncUnaryCall() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoadClient.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while (true) {
    maxOutstanding.acquireUninterruptibly();
    if (shutdown) {
      maxOutstanding.release();
      return;
    }
    ClientCalls.asyncUnaryCall(
        channel.newCall(LoadServer.GENERIC_UNARY_METHOD, CallOptions.DEFAULT),
        genericRequest.slice(),
        new StreamObserver<ByteBuf>() {
          long now = System.nanoTime();

          @Override
          public void onNext(ByteBuf value) {

          }

          @Override
          public void onError(Throwable t) {
            maxOutstanding.release();
            Level level = shutdown ? Level.FINE : Level.INFO;
            log.log(level, "Error in Generic Async Unary call", t);
          }

          @Override
          public void onCompleted() {
            delay(System.nanoTime() - now);
            maxOutstanding.release();
          }
        });
  }
}
 
Example 2
Source File: AbstractBenchmark.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Start a continuously executing set of unary calls that will terminate when
 * {@code done.get()} is true. Each completed call will increment the counter by the specified
 * delta which benchmarks can use to measure QPS or bandwidth.
 */
protected void startUnaryCalls(int callsPerChannel,
                               final AtomicLong counter,
                               final AtomicBoolean done,
                               final long counterDelta) {
  for (final ManagedChannel channel : channels) {
    for (int i = 0; i < callsPerChannel; i++) {
      StreamObserver<ByteBuf> observer = new StreamObserver<ByteBuf>() {
        @Override
        public void onNext(ByteBuf value) {
          counter.addAndGet(counterDelta);
        }

        @Override
        public void onError(Throwable t) {
          done.set(true);
        }

        @Override
        public void onCompleted() {
          if (!done.get()) {
            ByteBuf slice = request.slice();
            ClientCalls.asyncUnaryCall(
                channel.newCall(unaryMethod, CALL_OPTIONS), slice, this);
          }
        }
      };
      observer.onCompleted();
    }
  }
}
 
Example 3
Source File: GrpcClient.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
@Override
public void invokeAsync(final Endpoint endpoint, final Object request, final InvokeContext ctx,
                        final InvokeCallback callback, final long timeoutMs) {
    Requires.requireNonNull(endpoint, "endpoint");
    Requires.requireNonNull(request, "request");

    final Channel ch = getChannel(endpoint);
    final MethodDescriptor<Message, Message> method = getCallMethod(request);
    final CallOptions callOpts = CallOptions.DEFAULT.withDeadlineAfter(timeoutMs, TimeUnit.MILLISECONDS);
    final Executor executor = callback.executor() != null ? callback.executor() : DirectExecutor.INSTANCE;

    ClientCalls.asyncUnaryCall(ch.newCall(method, callOpts), (Message) request, new StreamObserver<Message>() {

        @Override
        public void onNext(final Message value) {
            executor.execute(() -> callback.complete(value, null));
        }

        @Override
        public void onError(final Throwable throwable) {
            executor.execute(() -> callback.complete(null, throwable));
        }

        @Override
        public void onCompleted() {
            // NO-OP
        }
    });
}
 
Example 4
Source File: DynamicGrpcClient.java    From milkman with MIT License 5 votes vote down vote up
private ListenableFuture<Void> callUnary(
    DynamicMessage request,
    StreamObserver<DynamicMessage> responseObserver,
    CallOptions callOptions) {
  DoneObserver<DynamicMessage> doneObserver = new DoneObserver<>();
  ClientCalls.asyncUnaryCall(
      createCall(callOptions),
      request,
      CompositeStreamObserver.of(responseObserver, doneObserver));
  return doneObserver.getCompletionFuture();
}
 
Example 5
Source File: HederaCall.java    From hedera-sdk-java with Apache License 2.0 5 votes vote down vote up
public void executeAsync(Client client, Duration retryTimeout, Consumer<Resp> onSuccess, Consumer<HederaThrowable> onError) {
    // Run local validator just before execute
    localValidate();

    final Consumer<Consumer<HederaThrowable>> executeCall = (onError2) -> ClientCalls.asyncUnaryCall(getChannel(client).newCall(getMethod(), CallOptions.DEFAULT), toProto(),
        new CallStreamObserver(onSuccess, onError2));

    new Backoff(RETRY_DELAY, retryTimeout)
        .asyncTryWhile(this::shouldRetry, executeCall, onError);
}
 
Example 6
Source File: DynamicClient.java    From karate-grpc with MIT License 5 votes vote down vote up
private ListenableFuture<Void> callUnary(
        DynamicMessage request,
        StreamObserver<DynamicMessage> responseObserver,
        CallOptions callOptions) {
    DoneObserver<DynamicMessage> doneObserver = new DoneObserver<>();
    ClientCalls.asyncUnaryCall(
            createCall(callOptions),
            request,
            ComponentObserver.of(responseObserver, doneObserver));
    return doneObserver.getCompletionFuture();
}
 
Example 7
Source File: ManageChannelProxy.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 8
Source File: Driver.java    From concurrency-limits with Apache License 2.0 5 votes vote down vote up
public void run() {
    long endTime = System.nanoTime() + this.runtime;
    while (true) {
        for (Driver.Segment segment : segments) {
            long segmentEndTime = System.nanoTime() + segment.duration();
            while (true) {
                long currentTime = System.nanoTime();
                if (currentTime > endTime) {
                    return;
                }
                
                if (currentTime > segmentEndTime) {
                    break;
                }
                
                long startTime = System.nanoTime();
                Uninterruptibles.sleepUninterruptibly(Math.max(0, segment.nextDelay()), TimeUnit.MILLISECONDS);
                ClientCalls.asyncUnaryCall(channel.newCall(TestServer.METHOD_DESCRIPTOR, CallOptions.DEFAULT.withWaitForReady()), "request",
                        new StreamObserver<String>() {
                            @Override
                            public void onNext(String value) {
                            }

                            @Override
                            public void onError(Throwable t) {
                                dropCounter.incrementAndGet();
                            }

                            @Override
                            public void onCompleted() {
                                latencyAccumulator.accept(System.nanoTime() - startTime);
                                successCounter.incrementAndGet();
                            }
                    });
            }
        }
    }
}
 
Example 9
Source File: LoadClient.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
  while (true) {
    maxOutstanding.acquireUninterruptibly();
    if (shutdown) {
      maxOutstanding.release();
      return;
    }
    ClientCalls.asyncUnaryCall(
        channel.newCall(LoadServer.GENERIC_UNARY_METHOD, CallOptions.DEFAULT),
        genericRequest.slice(),
        new StreamObserver<ByteBuf>() {
          long now = System.nanoTime();

          @Override
          public void onNext(ByteBuf value) {

          }

          @Override
          public void onError(Throwable t) {
            maxOutstanding.release();
            Level level = shutdown ? Level.FINE : Level.INFO;
            log.log(level, "Error in Generic Async Unary call", t);
          }

          @Override
          public void onCompleted() {
            delay(System.nanoTime() - now);
            maxOutstanding.release();
          }
        });
  }
}
 
Example 10
Source File: AbstractBenchmark.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Start a continuously executing set of unary calls that will terminate when
 * {@code done.get()} is true. Each completed call will increment the counter by the specified
 * delta which benchmarks can use to measure QPS or bandwidth.
 */
protected void startUnaryCalls(int callsPerChannel,
                               final AtomicLong counter,
                               final AtomicBoolean done,
                               final long counterDelta) {
  for (final ManagedChannel channel : channels) {
    for (int i = 0; i < callsPerChannel; i++) {
      StreamObserver<ByteBuf> observer = new StreamObserver<ByteBuf>() {
        @Override
        public void onNext(ByteBuf value) {
          counter.addAndGet(counterDelta);
        }

        @Override
        public void onError(Throwable t) {
          done.set(true);
        }

        @Override
        public void onCompleted() {
          if (!done.get()) {
            ByteBuf slice = request.slice();
            ClientCalls.asyncUnaryCall(
                channel.newCall(unaryMethod, CALL_OPTIONS), slice, this);
          }
        }
      };
      observer.onCompleted();
    }
  }
}
 
Example 11
Source File: EventServiceGrpc.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 */
public void process(Event request,
    io.grpc.stub.StreamObserver<Event> responseObserver) {
  ClientCalls.asyncUnaryCall(
      getChannel().newCall(getProcessMethod(), getCallOptions()), request, responseObserver);
}
 
Example 12
Source File: EventServiceGrpc.java    From micro-integrator with Apache License 2.0 4 votes vote down vote up
/**
 */
public void consume(Event request,
    io.grpc.stub.StreamObserver<com.google.protobuf.Empty> responseObserver) {
  ClientCalls.asyncUnaryCall(
      getChannel().newCall(getConsumeMethod(), getCallOptions()), request, responseObserver);
}
 
Example 13
Source File: ReportServiceGrpc.java    From istio-apim with Apache License 2.0 4 votes vote down vote up
/**
 */
public void report(org.wso2.apim.grpc.telemetry.receiver.generated.ReportRequest request,
    io.grpc.stub.StreamObserver<org.wso2.apim.grpc.telemetry.receiver.generated.ReportResponse> responseObserver) {
  ClientCalls.asyncUnaryCall(
      getChannel().newCall(getReportMethodHelper(), getCallOptions()), request, responseObserver);
}
 
Example 14
Source File: UniqueIdServiceGrpc.java    From Almost-Famous with MIT License 4 votes vote down vote up
/**
 * <pre>
 * Sends a unique id
 * </pre>
 */
public void getUniqueId(com.noseparte.common.rpc.service.UniqueIdRequest request,
    io.grpc.stub.StreamObserver<com.noseparte.common.rpc.service.UniqueIdResponse> responseObserver) {
  ClientCalls.asyncUnaryCall(
      getChannel().newCall(getGetUniqueIdMethod(), getCallOptions()), request, responseObserver);
}
 
Example 15
Source File: UniqueNameServiceGrpc.java    From Almost-Famous with MIT License 4 votes vote down vote up
/**
 * <pre>
 * Sends a unique id
 * </pre>
 */
public void uniqueName(com.noseparte.common.rpc.service.UniqueNameRequest request,
    io.grpc.stub.StreamObserver<com.noseparte.common.rpc.service.UniqueNameResponse> responseObserver) {
  ClientCalls.asyncUnaryCall(
      getChannel().newCall(getUniqueNameMethod(), getCallOptions()), request, responseObserver);
}