类io.grpc.Channel源码实例Demo

下面列出了怎么用io.grpc.Channel的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: grpc-swagger   文件: ChannelFactory.java
private static ClientInterceptor metadataInterceptor(Map<String, Object> metaDataMap) {
    return new ClientInterceptor() {
        @Override
        public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
                final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {

            return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
                @Override
                protected void checkedStart(Listener<RespT> responseListener, Metadata headers) {
                    metaDataMap.forEach((k, v) -> {
                        Key<String> mKey = Key.of(k, ASCII_STRING_MARSHALLER);
                        headers.put(mKey, String.valueOf(v));
                    });
                    delegate().start(responseListener, headers);
                }
            };
        }
    };
}
 
源代码2 项目: skywalking   文件: GRPCChannel.java
private GRPCChannel(String host, int port, List<ChannelBuilder> channelBuilders,
    List<ChannelDecorator> decorators) throws Exception {
    ManagedChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);

    for (ChannelBuilder builder : channelBuilders) {
        channelBuilder = builder.build(channelBuilder);
    }

    this.originChannel = channelBuilder.build();

    Channel channel = originChannel;
    for (ChannelDecorator decorator : decorators) {
        channel = decorator.build(channel);
    }

    channelWithDecorators = channel;
}
 
源代码3 项目: bazel-buildfarm   文件: ByteStreamServiceTest.java
@Test
public void missingBlobReadIsNotFound() {
  ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
  Digest digest = DIGEST_UTIL.compute(helloWorld);

  Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
  ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);

  when(simpleBlobStore.get(eq(digest.getHash()), any(OutputStream.class)))
      .thenReturn(immediateFuture(false));
  ReadRequest request =
      ReadRequest.newBuilder().setResourceName(createBlobDownloadResourceName(digest)).build();
  StatusRuntimeException notFoundException = null;
  try {
    if (service.read(request).hasNext()) {
      fail("no responses should be available");
    }
  } catch (StatusRuntimeException e) {
    assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Code.NOT_FOUND);
    notFoundException = e;
  }
  assertThat(notFoundException).isNotNull();
}
 
源代码4 项目: grpc-java   文件: CensusStatsModule.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  // New RPCs on client-side inherit the tag context from the current Context.
  TagContext parentCtx = tagger.getCurrentTagContext();
  final ClientCallTracer tracerFactory =
      newClientCallTracer(parentCtx, method.getFullMethodName());
  ClientCall<ReqT, RespT> call =
      next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory));
  return new SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      delegate().start(
          new SimpleForwardingClientCallListener<RespT>(responseListener) {
            @Override
            public void onClose(Status status, Metadata trailers) {
              tracerFactory.callEnded(status);
              super.onClose(status, trailers);
            }
          },
          headers);
    }
  };
}
 
源代码5 项目: java-docs-samples   文件: BookstoreClient.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) {
  LOGGER.info("Intercepted " + method.getFullMethodName());
  ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);

  call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
    @Override
    public void start(Listener<RespT> responseListener, Metadata headers) {
      if (apiKey != null && !apiKey.isEmpty()) {
        LOGGER.info("Attaching API Key: " + apiKey);
        headers.put(API_KEY_HEADER, apiKey);
      }
      if (authToken != null && !authToken.isEmpty()) {
        System.out.println("Attaching auth token");
        headers.put(AUTHORIZATION_HEADER, "Bearer " + authToken);
      }
      super.start(responseListener, headers);
    }
  };
  return call;
}
 
源代码6 项目: brave   文件: BaseITTracingClientInterceptor.java
@Test public void userInterceptor_throwsOnHalfClose() {
  closeClient(client);
  client = newClient(new ClientInterceptor() {
    @Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
        Channel channel) {
      ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
      return new SimpleForwardingClientCall<ReqT, RespT>(call) {
        @Override public void halfClose() {
          throw new IllegalStateException("I'm a bad interceptor.");
        }
      };
    }
  }, grpcTracing.newClientInterceptor());

  assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
      .isInstanceOf(IllegalStateException.class);
  testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
 
源代码7 项目: grpc-java   文件: AltsProtocolNegotiator.java
/**
 * Creates a protocol negotiator for ALTS on the server side.
 */
public static ProtocolNegotiator serverAltsProtocolNegotiator(
    ObjectPool<Channel> handshakerChannelPool) {
  final LazyChannel lazyHandshakerChannel = new LazyChannel(handshakerChannelPool);
  final class ServerTsiHandshakerFactory implements TsiHandshakerFactory {

    @Override
    public TsiHandshaker newHandshaker(@Nullable String authority) {
      assert authority == null;
      return AltsTsiHandshaker.newServer(
          HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()),
          new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions()));
    }
  }

  return new ServerAltsProtocolNegotiator(
      new ServerTsiHandshakerFactory(), lazyHandshakerChannel);
}
 
源代码8 项目: android-docs-samples   文件: SpeechService.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
        final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
        final Channel next) {
    return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
            next.newCall(method, callOptions)) {
        @Override
        protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
                throws StatusException {
            Metadata cachedSaved;
            URI uri = serviceUri(next, method);
            synchronized (this) {
                Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
                if (mLastMetadata == null || mLastMetadata != latestMetadata) {
                    mLastMetadata = latestMetadata;
                    mCached = toHeaders(mLastMetadata);
                }
                cachedSaved = mCached;
            }
            headers.merge(cachedSaved);
            delegate().start(responseListener, headers);
        }
    };
}
 
源代码9 项目: dgraph4j   文件: ClientRandomStubTest.java
@Test
public void testClientRandomStubTest() throws IllegalAccessException {
  int NUM_ITER = 1000;
  HashMap<String, Integer> counts = new HashMap<>();
  for (int i = 0; i < NUM_ITER; i++) {
    Transaction txn = dgraphClient.newTransaction();
    Channel channel = (Channel) channelField.get(stubField.get(asyncTransactionField.get(txn)));
    String endpoint = channel.authority();
    counts.put(endpoint, counts.getOrDefault(endpoint, 0) + 1);
  }

  // Ensure that we got all the clients
  assertEquals(counts.size(), 3);
  int sum = 0;
  for (Map.Entry<String, Integer> ep : counts.entrySet()) {
    assertTrue(ep.getValue() > 300);
    sum += ep.getValue();
  }

  assertEquals(sum, NUM_ITER);
}
 
源代码10 项目: pampas   文件: GrpcWorker.java
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        GrpcWorker worker = new GrpcWorker();
        //"test.proto"
//        String protilFileName = "test.proto";
//        ProtoFile protoFile = worker.parserProtoFile(protilFileName);
//        //  "/v1/example/hello"
//        worker.listProtoServiceInProtoFile(protoFile);
//        GrpcServiceDefine grpcService = worker.findGrpcService("/v1/example/hello", "post");
//        System.out.println("grpcService:" + grpcService);

        DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(URLTools.toUrl(Consts.JAVA_OUT_DIR));

        Class grpc = loader.loadClass("df.open.grpc.hello.HelloServiceGrpc");
        Class proto = loader.loadClass("df.open.grpc.hello.HelloServiceProto");

        Method newBlockingStub = grpc.getMethod("newBlockingStub", Channel.class);
        System.out.println(newBlockingStub);
        AbstractStub stub = (AbstractStub) newBlockingStub.invoke(grpc, channel);
        System.out.println(stub);

    }
 
源代码11 项目: grpc-swagger   文件: GrpcReflectionUtils.java
public static FileDescriptorSet resolveService(Channel channel, String serviceName) {
    ServerReflectionClient reflectionClient = ServerReflectionClient.create(channel);
    try {
        List<String> serviceNames = reflectionClient.listServices().get();
        if (!serviceNames.contains(serviceName)) {
            throw Status.NOT_FOUND.withDescription(
                    String.format("Remote server does not have service %s. Services: %s", serviceName, serviceNames))
                    .asRuntimeException();
        }

        return reflectionClient.lookupService(serviceName).get();
    } catch (InterruptedException | ExecutionException e) {
        logger.error("Resolve services get error", e);
        throw new RuntimeException(e);
    }
}
 
源代码12 项目: rapid   文件: GrpcClient.java
public GrpcClient(final Endpoint address, final SharedResources sharedResources, final ISettings settings) {
    this.address = address;
    this.settings = settings;
    this.grpcExecutor = sharedResources.getClientChannelExecutor();
    this.backgroundExecutor = sharedResources.getBackgroundExecutor();
    this.eventLoopGroup = settings.getUseInProcessTransport() ? null : sharedResources.getEventLoopGroup();
    final RemovalListener<Endpoint, Channel> removalListener =
            removal -> shutdownChannel((ManagedChannel) removal.getValue());
    this.channelMap = CacheBuilder.newBuilder()
            .expireAfterAccess(30, TimeUnit.SECONDS)
            .removalListener(removalListener)
            .build(new CacheLoader<Endpoint, Channel>() {
                @Override
                public Channel load(final Endpoint endpoint) {
                    return getChannel(endpoint);
                }
            });
}
 
源代码13 项目: grpc-java   文件: AsyncClient.java
private void warmup(SimpleRequest req, List<? extends Channel> channels) throws Exception {
  long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(config.warmupDuration);
  doBenchmark(req, channels, endTime);
  // I don't know if this helps, but it doesn't hurt trying. We sometimes run warmups
  // of several minutes at full load and it would be nice to start the actual benchmark
  // with a clean heap.
  System.gc();
}
 
SimulatedRemoteMesosSchedulerDriver(Protos.MasterInfo masterInfo, Channel channel, Scheduler callbackHandler, TitusRuntime titusRuntime) {
    this.masterInfo = masterInfo;
    this.asyncClient = SimulatedMesosServiceGrpc.newStub(channel);
    this.blockingClient = SimulatedMesosServiceGrpc.newBlockingStub(channel);
    this.callbackHandler = callbackHandler;
    this.titusRuntime = titusRuntime;
}
 
@Bean(name = TITUS_MASTER_CHANNEL)
public Channel getManagedChannel(TitusMasterClientConfiguration configuration, LeaderResolver leaderResolver, TitusRuntime titusRuntime) {
    return NettyChannelBuilder
            .forTarget("leader://titusmaster")
            .nameResolverFactory(new LeaderNameResolverFactory(leaderResolver, configuration.getMasterGrpcPort(), titusRuntime))
            .usePlaintext(true)
            .maxHeaderListSize(65536)
            .build();
}
 
源代码16 项目: brave   文件: BaseITTracingClientInterceptor.java
/**
 * NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
 *
 * <p>Also notice that we are only making the current context available in the request side.
 */
@Test public void currentSpanVisibleToUserInterceptors() {
  closeClient(client);

  client = newClient(
      new ClientInterceptor() {
        @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) {
              tracing.tracer().currentSpanCustomizer().annotate("start");
              super.start(responseListener, headers);
            }

            @Override public void sendMessage(ReqT message) {
              tracing.tracer().currentSpanCustomizer().annotate("sendMessage");
              super.sendMessage(message);
            }
          };
        }
      },
      grpcTracing.newClientInterceptor()
  );

  GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);

  assertThat(testSpanHandler.takeRemoteSpan(CLIENT).annotations())
      .extracting(Entry::getValue)
      .containsOnly("start", "sendMessage");
}
 
源代码17 项目: grpc-nebula-java   文件: CustomHeaderClient.java
/**
 * A custom client.
 */
private CustomHeaderClient(String host, int port) {
  originChannel = ManagedChannelBuilder.forAddress(host, port)
      .usePlaintext()
      .build();
  ClientInterceptor interceptor = new HeaderClientInterceptor();
  Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
  blockingStub = GreeterGrpc.newBlockingStub(channel);
}
 
源代码18 项目: pinpoint   文件: DiscardClientInterceptor.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
    if (MethodDescriptor.MethodType.CLIENT_STREAMING == method.getType()) {
        if (logger.isDebugEnabled()) {
            logger.debug("interceptCall {}", method.getFullMethodName());
        }
        final ClientCall<ReqT, RespT> newCall = next.newCall(method, callOptions);
        return new DiscardClientCall<ReqT, RespT>(newCall, this.listener, maxPendingThreshold);
    } else {
        return next.newCall(method, callOptions);
    }
}
 
@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(channel)
      .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));
}
 
源代码20 项目: grpc-nebula-java   文件: TesterActivity.java
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
    MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
  return new CheckedForwardingClientCall<ReqT, RespT>(
      next.newCall(method.toBuilder().setSafe(true).build(), callOptions)) {
    @Override
    public void checkedStart(Listener<RespT> responseListener, Metadata headers) {
      delegate().start(responseListener, headers);
    }
  };
}
 
源代码21 项目: micronaut-grpc   文件: GrpcChannelScope.java
@Override
public <T> T get(
        BeanResolutionContext resolutionContext,
        BeanDefinition<T> beanDefinition,
        BeanIdentifier identifier,
        Provider<T> provider) {
    BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
            new IllegalStateException("@GrpcChannel used in invalid location")
    );
    Argument argument = segment.getArgument();
    String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
    if (StringUtils.isEmpty(value)) {
        throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
    }
    if (!Channel.class.isAssignableFrom(argument.getType())) {
        throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
    }

    if ("grpc-server".equalsIgnoreCase(value)) {
        return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
    }

    if (!(provider instanceof ParametrizedProvider)) {
        throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
    }
    value = applicationContext.resolveRequiredPlaceholders(value);
    String finalValue = value;
    return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
            (ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
    );
}
 
源代码22 项目: titus-control-plane   文件: LoadGeneratorMain.java
@Bean
@Named(GATEWAY_CHANNEL)
public Channel getGatewayChannel(ApplicationArguments arguments) {
    List<String> gateway = arguments.getOptionValues("gateway");

    String gatewayAddress = CollectionsExt.isNullOrEmpty(gateway) ? "localhost:8091" : gateway.get(0);

    return NettyChannelBuilder
            .forTarget(gatewayAddress)
            .usePlaintext(true)
            .maxHeaderListSize(65536)
            .build();
}
 
源代码23 项目: saluki   文件: AbstractClientInvocation.java
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  if (ReflectUtils.isToStringMethod(method)) {
    return AbstractClientInvocation.this.toString();
  } else {
    GrpcRequest request = this.buildGrpcRequest(method, args);
    MethodType methodType = request.getMethodType();
    Channel channel = request.getChannel();
    try {
      switch (methodType) {
        case UNARY:
          return unaryCall(request, channel);
        case CLIENT_STREAMING:
          return streamCall(request, channel);
        case SERVER_STREAMING:
          return streamCall(request, channel);
        case BIDI_STREAMING:
          return streamCall(request, channel);
        default:
          RpcServiceException rpcFramwork =
              new RpcServiceException(RpcErrorMsgConstant.SERVICE_UNFOUND);
          throw rpcFramwork;
      }
    } finally {
      Object remote = GrpcCallOptions.getAffinity(request.getRefUrl())
          .get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY);
      log.debug(String.format("Service: %s  Method: %s  RemoteAddress: %s",
          request.getServiceName(), request.getMethodName(), String.valueOf(remote)));
    }
  }
}
 
public ThrottlingBlockingClient(Channel channel, String token) {
    ThrottlingTestServiceGrpc.ThrottlingTestServiceBlockingStub stub =
            ThrottlingTestServiceGrpc.newBlockingStub(channel);
    //add metadata
    Metadata metadata = new Metadata();
    metadata.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), token);
    blockingStub = MetadataUtils.attachHeaders(stub,metadata);
}
 
源代码25 项目: grpc-nebula-java   文件: OpenLoopClient.java
LoadGenerationWorker(Channel channel, SimpleRequest request, int targetQps, int duration) {
  stub = BenchmarkServiceGrpc.newStub(checkNotNull(channel, "channel"));
  this.request = checkNotNull(request, "request");
  this.targetQps = targetQps;
  numRpcs = (long) targetQps * duration;
  rnd = new Random();
}
 
源代码26 项目: grpc-java   文件: AltsProtocolNegotiator.java
/**
 * If channel is null, gets a channel from the channel pool, otherwise, returns the cached
 * channel.
 */
synchronized Channel get() {
  if (channel == null) {
    channel = channelPool.getObject();
  }
  return channel;
}
 
源代码27 项目: grpc-java   文件: ManagedChannelImplTest.java
@Test
public void binaryLogInstalled() throws Exception {
  final SettableFuture<Boolean> intercepted = SettableFuture.create();
  channelBuilder.binlog = new BinaryLog() {
    @Override
    public void close() throws IOException {
      // noop
    }

    @Override
    public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(
        ServerMethodDefinition<ReqT, RespT> oMethodDef) {
      return oMethodDef;
    }

    @Override
    public Channel wrapChannel(Channel channel) {
      return ClientInterceptors.intercept(channel,
          new ClientInterceptor() {
            @Override
            public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
                MethodDescriptor<ReqT, RespT> method,
                CallOptions callOptions,
                Channel next) {
              intercepted.set(true);
              return next.newCall(method, callOptions);
            }
          });
    }
  };

  createChannel();
  ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
  call.start(mockCallListener, new Metadata());
  assertTrue(intercepted.get());
}
 
源代码28 项目: reactive-grpc   文件: BackpressureController.java
@FXML
public void initialize() throws Exception {
    Server server = ServerBuilder.forPort(9000).addService(this).build().start();
    Channel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
    stub = RxBackpressureDemoGrpc.newRxStub(channel);

    producedSeries.setName("Produced");
    consumedSeries.setName("Consumed");
    lineChart.getData().add(producedSeries);
    lineChart.getData().add(consumedSeries);
}
 
源代码29 项目: etherjar   文件: EmeraldTransport.java
public EmeraldTransport(Channel channel,
                        ObjectMapper objectMapper,
                        RpcConverter rpcConverter,
                        ExecutorService executorService,
                        Common.ChainRef chainRef) {
    this.channel = channel;
    this.objectMapper = objectMapper;
    this.rpcConverter = rpcConverter;
    this.executorService = executorService;
    this.chainRef = chainRef;
    blockingStub = BlockchainGrpc.newBlockingStub(channel);
}
 
源代码30 项目: grpc-nebula-java   文件: ManagedChannelImpl.java
@Override
public Channel asChannel() {
  return new SubchannelChannel(
      subchannel, balancerRpcExecutorHolder.getExecutor(),
      transportFactory.getScheduledExecutorService(),
      callTracerFactory.create());
}
 
 类所在包
 类方法
 同包方法