Java 类io.grpc.ManagedChannel 实例源码

项目:africastalking-android    文件:Service.java   
protected ClientTokenResponse fetchToken(String host, int port) throws IOException {

        if (LOGGING) { LOGGER.log("Fetching token..."); }

        ManagedChannel channel = getChannel(host, port);
        SdkServerServiceBlockingStub stub = addClientIdentification(SdkServerServiceGrpc.newBlockingStub(channel));
        ClientTokenRequest req = ClientTokenRequest.newBuilder().build();
        ClientTokenResponse token = stub.getToken(req);

        if (LOGGING) {
            LOGGER.log(
                "\n\nToken: %s\nUsername: %s\nEnvironment: %s\nExpires: %s\n\n",
                token.getToken(),
                token.getUsername(),
                token.getEnvironment(),
                String.valueOf(token.getExpiration()));
        }
        return token;
    }
项目:grpc-samples-java    文件:GreeterClient.java   
public static void main(String[] args) throws InterruptedException {

        // Create a channel
        ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT)
                .usePlaintext(true)
                .build();

        // Create a blocking stub with the channel
        GreetingServiceGrpc.GreetingServiceBlockingStub stub = 
                GreetingServiceGrpc.newBlockingStub(channel);

        // Create a request
        HelloRequest request = HelloRequest.newBuilder()
                .setName("Mete - on Java")
                .setAge(34)
                .setSentiment(Sentiment.HAPPY)
                .build();

        // Send the request using the stub
        System.out.println("GreeterClient sending request");
        HelloResponse helloResponse = stub.greeting(request);

        System.out.println("GreeterClient received response: " + helloResponse.getGreeting());

        //channel.shutdown();
    }
项目:incubator-servicecomb-saga    文件:GrpcClientMessageSender.java   
public GrpcClientMessageSender(
    String address,
    ManagedChannel channel,
    MessageSerializer serializer,
    MessageDeserializer deserializer,
    ServiceConfig serviceConfig,
    Function<MessageSender, Runnable> errorHandlerFactory,
    MessageHandler handler) {
  this.target = address;
  this.asyncEventService = TxEventServiceGrpc.newStub(channel);
  this.blockingEventService = TxEventServiceGrpc.newBlockingStub(channel);
  this.serializer = serializer;

  this.compensateStreamObserver = new GrpcCompensateStreamObserver(handler, errorHandlerFactory.apply(this), deserializer);
  this.serviceConfig = serviceConfig(serviceConfig.serviceName(), serviceConfig.instanceId());
}
项目:JungleTree    文件:PluginGrpcServer.java   
public void connectPlugin(String host, int port) {
    ManagedChannel channel = NettyChannelBuilder.forAddress(host, port)
            .negotiationType(NegotiationType.PLAINTEXT) // TODO: gRPC encryption
            .keepAliveTime(1, TimeUnit.MINUTES)
            .keepAliveTimeout(5, TimeUnit.SECONDS)
            .directExecutor()
            .channelType(EpollSocketChannel.class)
            .eventLoopGroup(new EpollEventLoopGroup())
            .build();

    PluginManagerGrpc.PluginManagerBlockingStub blocking = PluginManagerGrpc.newBlockingStub(channel);
    PluginManagerGrpc.PluginManagerStub async = PluginManagerGrpc.newStub(channel);

    ServiceConnection connection = ServiceConnection.builder()
            .channel(channel)
            .blockingStub(blocking)
            .asyncStub(async)
            .build();

    this.pluginConnections.put(PLUGIN_MANAGER, connection);
}
项目:haystack-client-java    文件:GRPCAgentClient.java   
public GRPCAgentClient build() {

            ManagedChannel managedChannel = channel;

            if (managedChannel == null) {
                managedChannel = NettyChannelBuilder.forAddress(host, port)
                    .keepAliveTime(keepAliveTimeMS, TimeUnit.MILLISECONDS)
                    .keepAliveTimeout(keepAliveTimeoutMS, TimeUnit.MILLISECONDS)
                    .keepAliveWithoutCalls(keepAliveWithoutCalls)
                    .negotiationType(negotiationType)
                    .build();
            }

            SpanAgentStub stub = SpanAgentGrpc.newStub(managedChannel);

            return new GRPCAgentClient(format, managedChannel, stub, observer, shutdownTimeoutMS);
        }
项目:vertx-zero    文件:RpcSslTool.java   
/**
 * @param vertx  Vert.x instance
 * @param config configuration
 * @return ManagedChannel
 */
public static ManagedChannel getChannel(final Vertx vertx,
                                        final JsonObject config) {
    final String rpcHost = config.getString(Key.HOST);
    final Integer rpcPort = config.getInteger(Key.PORT);
    LOGGER.info(Info.CLIENT_RPC, rpcHost, String.valueOf(rpcPort));
    final VertxChannelBuilder builder =
            VertxChannelBuilder
                    .forAddress(vertx, rpcHost, rpcPort);
    Fn.safeSemi(null != config.getValue(Key.SSL), LOGGER,
            () -> {
                final JsonObject sslConfig = config.getJsonObject(Key.SSL);
                if (null != sslConfig && !sslConfig.isEmpty()) {
                    final Object type = sslConfig.getValue("type");
                    final CertType certType = null == type ?
                            CertType.PEM : Types.fromStr(CertType.class, type.toString());
                    final TrustPipe<JsonObject> pipe = TrustPipe.get(certType);
                    // Enable SSL
                    builder.useSsl(pipe.parse(sslConfig));
                } else {
                    builder.usePlaintext(true);
                }
            });
    return builder.build();
}
项目:vertx-zero    文件:UnitySpear.java   
@Override
public Future<Envelop> send(
        final Vertx vertx,
        final IpcData data) {
    // Channel
    final ManagedChannel channel = RpcSslTool.getChannel(vertx, data);
    final UnityServiceGrpc.UnityServiceVertxStub stub
            = UnityServiceGrpc.newVertxStub(channel);
    // Request
    final IpcRequest request = DataEncap.in(data);
    // Call and return to future
    final Future<Envelop> handler = Future.future();
    stub.unityCall(request, response ->
            // Reply
            RpcRepdor.create(getClass()).reply(handler, response));
    return handler;
}
项目:google-assistant-java-demo    文件:AssistantClient.java   
public AssistantClient(OAuthCredentials oAuthCredentials, AssistantConf assistantConf, DeviceModel deviceModel,
                       Device device) {

    this.assistantConf = assistantConf;
    this.deviceModel = deviceModel;
    this.device = device;
    this.currentConversationState = ByteString.EMPTY;

    // Create a channel to the test service.
    ManagedChannel channel = ManagedChannelBuilder.forAddress(assistantConf.getAssistantApiEndpoint(), 443)
            .build();

    // Create a stub with credential
    embeddedAssistantStub = EmbeddedAssistantGrpc.newStub(channel);

    updateCredentials(oAuthCredentials);
}
项目:microservice-skeleton    文件:GreeterServiceConsumer.java   
public void greet(String name, String message) {

        if (discoveryClient == null) {
            logger.info("Discovery client is null");
        } else {
            logger.info("Discovery client is not null");
            try {
                List<ServiceInstance> servers = discoveryClient.getInstances("service-account");

                for (ServiceInstance server : servers) {
                    String hostName = server.getHost();
                    int gRpcPort = Integer.parseInt(server.getMetadata().get("grpc.port"));
                    logger.info("=====>> " + hostName + " ---- " + gRpcPort);

                    final ManagedChannel channel = ManagedChannelBuilder.forAddress(hostName, gRpcPort)
                            .usePlaintext(true)
                            .build();
                    final GreetingGrpc.GreetingFutureStub stub = GreetingGrpc.newFutureStub(channel);

                    stub.sayHi(HelloRequest.newBuilder().setName(name).setMessage(message).build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
项目:GoogleAssistantSDK    文件:SpeechService.java   
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
项目:GoogleAssistantSDK    文件:SpeechService.java   
private void fetchAccessToken() {


        ManagedChannel channel = ManagedChannelBuilder.forTarget(HOSTNAME).build();
        try {
            mApi = EmbeddedAssistantGrpc.newStub(channel)
                    .withCallCredentials(MoreCallCredentials.from(
                            Credentials_.fromResource(getApplicationContext(), R.raw.credentials)
                    ));
        } catch (IOException|JSONException e) {
            Log.e(TAG, "error creating assistant service:", e);
        }

        for (Listener listener : mListeners) {
            listener. onCredentioalSuccess();

        }

    }
项目:tikv-client-lib-java    文件:PDClient.java   
private boolean createLeaderWrapper(String leaderUrlStr) {
  try {
    URL tURL = new URL(leaderUrlStr);
    HostAndPort newLeader = HostAndPort.fromParts(tURL.getHost(), tURL.getPort());
    leaderUrlStr = newLeader.toString();
    if (leaderWrapper != null && leaderUrlStr.equals(leaderWrapper.getLeaderInfo())) {
      return true;
    }

    // create new Leader
    ManagedChannel clientChannel = session.getChannel(leaderUrlStr);
    leaderWrapper =
      new LeaderWrapper(
          leaderUrlStr,
          PDGrpc.newBlockingStub(clientChannel),
          PDGrpc.newStub(clientChannel),
          System.nanoTime());
  } catch (MalformedURLException e) {
    logger.error("Error updating leader.", e);
    return false;
  }
  logger.info(String.format("Switched to new leader: %s", leaderWrapper));
  return true;
}
项目:tikv-client-lib-java    文件:RegionStoreClient.java   
public static RegionStoreClient create(
    TiRegion region, Store store, TiSession session) {
  RegionStoreClient client;
  String addressStr = store.getAddress();
  if (logger.isDebugEnabled()) {
    logger.debug(String.format("Create region store client on address %s", addressStr));
  }
  ManagedChannel channel = session.getChannel(addressStr);

  TikvBlockingStub blockingStub = TikvGrpc.newBlockingStub(channel);

  TikvStub asyncStub = TikvGrpc.newStub(channel);
  client =
      new RegionStoreClient(region, session, blockingStub, asyncStub);
  return client;
}
项目:tikv-client-lib-java    文件:TiSession.java   
public synchronized ManagedChannel getChannel(String addressStr) {
  ManagedChannel channel = connPool.get(addressStr);
  if (channel == null) {
    HostAndPort address;
    try {
      address = HostAndPort.fromString(addressStr);
    } catch (Exception e) {
      throw new IllegalArgumentException("failed to form address");
    }

    // Channel should be lazy without actual connection until first call
    // So a coarse grain lock is ok here
    channel = ManagedChannelBuilder.forAddress(address.getHostText(), address.getPort())
        .maxInboundMessageSize(conf.getMaxFrameSize())
        .usePlaintext(true)
        .idleTimeout(60, TimeUnit.SECONDS)
        .build();
    connPool.put(addressStr, channel);
  }
  return channel;
}
项目:africastalking-java    文件:ATServerTest.java   
@BeforeClass
public static void startServer() throws IOException {
    AfricasTalking.initialize(Fixtures.USERNAME, Fixtures.API_KEY);
    server = new Server(new Authenticator() {
        @Override
        public boolean authenticate(String client) {
            return client.compareToIgnoreCase(TEST_CLIENT_ID) == 0;
        }
    });
    server.addSipCredentials("test", "secret", "sip://at.dev");
    server.start(certFile, privateKeyFile, TEST_PORT);

    ManagedChannel ch = NettyChannelBuilder.forAddress("localhost", TEST_PORT)
        .sslContext(GrpcSslContexts.forClient().trustManager(certFile).build())
        .build();


    client = SdkServerServiceGrpc.newBlockingStub(ch)
        .withCallCredentials(new CallCredentials(){
            @Override
            public void applyRequestMetadata(MethodDescriptor<?, ?> method, Attributes attrs, Executor appExecutor,
                    final MetadataApplier applier) {
                        appExecutor.execute(new Runnable(){
                            @Override
                            public void run() {
                                try {
                                    Metadata headers = new Metadata();
                                    Metadata.Key<String> clientIdKey = Metadata.Key.of("X-Client-Id", Metadata.ASCII_STRING_MARSHALLER);
                                    headers.put(clientIdKey, TEST_CLIENT_ID);
                                    applier.apply(headers);
                                } catch(Throwable ex) {
                                    applier.fail(Status.UNAUTHENTICATED.withCause(ex));
                                }
                            }
                        });

            }
        });
}
项目:ms-grpc    文件:GreetTest.java   
@Test
public void getMessage(){
    ManagedChannel channel = ManagedChannelBuilder
            .forAddress("127.0.0.1",50051)
            .usePlaintext(true)
            .build();
    GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName("gggg").build();
    HelloReply response;
    blockingStub.sayHello(request);

    try {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
项目:seldon-core    文件:SeldonGrpcServer.java   
/**
 * Using the principal from authorization return a client gRPC channel to connect to the engine running the prediction graph.
 * @return ManagedChannel
 */
public ManagedChannel getChannel() {
    final String principal = getPrincipal();
    if (principal == null )
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_GRPC_NO_PRINCIPAL_FOUND,"");
    }

    final DeploymentSpec deploymentSpec = deploymentStore.getDeployment(principal);
    if (deploymentSpec == null)
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_NO_RUNNING_DEPLOYMENT,"Principal is "+principal);
    }

    ManagedChannel channel = channelStore.get(principal);
    if (channel == null)
    {
        throw new SeldonAPIException(SeldonAPIException.ApiExceptionType.APIFE_GRPC_NO_GRPC_CHANNEL_FOUND,"Principal is "+principal);
    }
    return channel;
}
项目:dockerized-microservices    文件:PasswordsServiceClient.java   
/**
 * A client to call the GRPC find password service
 * @param param Query
 * @return Map of the GRPC service response
 */
public PasswordsResponseDto findPasswordMatches(String param) {
    ManagedChannel managedChannel = passwordsServiceManagedChannelSupplier.get();
    FindPasswordsQuery query = FindPasswordsQuery.newBuilder()
            .setQuery(param).build();

    FindPasswordsResponse response = PasswordsServiceGrpc
            .newBlockingStub(managedChannel)
            .withDeadlineAfter(grpcTimeout, TimeUnit.MILLISECONDS)
            .withInterceptors(interceptor)
            .findPasswords(query);

    PasswordsResponseDto.PasswordsResponseDtoBuilder responseDtoBuilder = PasswordsResponseDto.builder()
            .totalMatches(response.getNumOfMatches());

    if(!CollectionUtils.isEmpty(response.getMatchesList())) {
        responseDtoBuilder.matches(response.getMatchesList());
    }
    else {
        responseDtoBuilder.matches(Collections.emptyList());
    }

    return responseDtoBuilder.build();
}
项目:black-mirror    文件:SpeechService.java   
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
项目:black-mirror    文件:SpeechService.java   
@Override
protected void onPostExecute(AccessToken accessToken) {
    mAccessTokenTask = null;
    final ManagedChannel channel = new OkHttpChannelProvider()
            .builderForAddress(HOSTNAME, PORT)
            .nameResolverFactory(new DnsNameResolverProvider())
            .intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
                    .createScoped(SCOPE)))
            .build();
    mApi = SpeechGrpc.newStub(channel);

    // Schedule access token refresh before it expires
    if (mHandler != null) {
        mHandler.postDelayed(mFetchAccessTokenRunnable,
                Math.max(accessToken.getExpirationTime().getTime()
                        - System.currentTimeMillis()
                        - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
    }
}
项目:grpcx    文件:ChannelFactory.java   
public static ManagedChannel getChannel(String serviceName)
{
    HostInfo hostInfo=LoadBalance.getHostInfo(serviceName);
    if(hostInfo==null)
        return null;
    synchronized (ChannelFactory.class) {
        if(serviceChannels.get(hostInfo)!=null)
        {
            return serviceChannels.get(hostInfo);
        }
        else 
        {
            ManagedChannel channel=ManagedChannelBuilder.forAddress(hostInfo.getIp(), Integer.valueOf(hostInfo.getPort()))
                    .usePlaintext(true)
                    .build();
            serviceChannels.put(hostInfo, channel);
            return channel;
        }
    }

}
项目:grpcx    文件:ChannelFactory.java   
public static void shutDownChannel(HostInfo hostInfo)
{
    ManagedChannel channel=serviceChannels.get(hostInfo);
    try {
        if(channel!=null&&!channel.isShutdown())
        {
            channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally {
        serviceChannels.remove(hostInfo);
    }
}
项目:jetcd    文件:ClientConnectionManager.java   
<T extends AbstractStub<T>, R> CompletableFuture<R> withNewChannel(
    String endpoint,
    Function<ManagedChannel, T> stubCustomizer,
    Function<T, CompletableFuture<R>> stubConsumer) {

  final ManagedChannel channel = defaultChannelBuilder()
      .nameResolverFactory(
          forEndpoints(
              Optional.ofNullable(builder.authority()).orElse("etcd"),
              Collections.singleton(endpoint),
              Optional.ofNullable(builder.uriResolverLoader())
                  .orElseGet(URIResolverLoader::defaultLoader)
          )
      ).build();

  try {
    T stub = stubCustomizer.apply(channel);

    return stubConsumer.apply(stub).whenComplete(
        (r, t) -> channel.shutdown()
    );
  } catch (Exception e) {
    channel.shutdown();
    throw EtcdExceptionFactory.toEtcdException(e);
  }
}
项目:grpc-java-by-example    文件:SimpleEchoClient.java   
public static void main(String[] args) throws InterruptedException, UnknownHostException {
  String host = System.getenv("ECHO_SERVICE_HOST");
  String port = System.getenv("ECHO_SERVICE_PORT");
  final ManagedChannel channel = ManagedChannelBuilder.forAddress(host, Integer.valueOf(port))
      .usePlaintext(true)
      .build();

  final String self = InetAddress.getLocalHost().getHostName();

  ExecutorService executorService = Executors.newFixedThreadPool(THREADS);
  for (int i = 0; i < THREADS; i++) {
    EchoServiceGrpc.EchoServiceBlockingStub stub = EchoServiceGrpc.newBlockingStub(channel);
    executorService.submit(() -> {
      while (true) {
        EchoResponse response = stub.echo(EchoRequest.newBuilder()
            .setMessage(self + ": " + Thread.currentThread().getName())
            .build());
        System.out.println(response.getFrom() + " echoed");

        Thread.sleep(RANDOM.nextInt(700));
      }
    });
  }
}
项目:grpc-java-by-example    文件:MyGrpcClient.java   
public static void main(String[] args) throws InterruptedException {
  ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 8080)
      .usePlaintext(true)
      .build();

  GreetingServiceGrpc.GreetingServiceBlockingStub stub =
      GreetingServiceGrpc.newBlockingStub(channel);

  HelloResponse helloResponse = stub.greeting(
      HelloRequest.newBuilder()
          .setName("Ray")
          .setAge(18)
          .setSentiment(Sentiment.HAPPY)
          .build());

  System.out.println(helloResponse);

  channel.shutdown();
}
项目:java-app-sdk    文件:AsyncDiscovery.java   
/**
 * Build an AsyncDiscovery wrapper from Host and Port
 *
 * @param _host The server host
 * @param _port The server port
 * @return An Observable stream containing the newly built AsyncDiscovery wrapper
 */
public static Observable<AsyncDiscovery> from(String _host, int _port) {
    return Observable
            .create((Subscriber<? super AsyncDiscovery> t) -> {
                try {
                    ManagedChannel ch = ManagedChannelBuilder
                            .forAddress(_host, _port)
                            .usePlaintext(true)
                            .build();
                    DiscoveryGrpc.DiscoveryFutureStub stub1 = DiscoveryGrpc.newFutureStub(ch);
                    t.onNext(new AsyncDiscovery(stub1));
                    t.onCompleted();
                } catch (Exception ex) {
                    t.onError(ex);
                }
            });
}
项目:fabric-sdk-java    文件:OrdererClient.java   
synchronized void shutdown(boolean force) {

        if (shutdown) {
            return;
        }
        shutdown = true;
        ManagedChannel lchannel = managedChannel;
        managedChannel = null;
        if (lchannel == null) {
            return;
        }
        if (force) {
            lchannel.shutdownNow();
        } else {
            boolean isTerminated = false;

            try {
                isTerminated = lchannel.shutdown().awaitTermination(3, TimeUnit.SECONDS);
            } catch (Exception e) {
                logger.debug(e); //best effort
            }
            if (!isTerminated) {
                lchannel.shutdownNow();
            }
        }
    }
项目:android-docs-samples    文件:SpeechService.java   
@Override
public void onDestroy() {
    super.onDestroy();
    mHandler.removeCallbacks(mFetchAccessTokenRunnable);
    mHandler = null;
    // Release the gRPC channel.
    if (mApi != null) {
        final ManagedChannel channel = (ManagedChannel) mApi.getChannel();
        if (channel != null && !channel.isShutdown()) {
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down the gRPC channel.", e);
            }
        }
        mApi = null;
    }
}
项目:android-docs-samples    文件:SpeechService.java   
@Override
protected void onPostExecute(AccessToken accessToken) {
    mAccessTokenTask = null;
    final ManagedChannel channel = new OkHttpChannelProvider()
            .builderForAddress(HOSTNAME, PORT)
            .nameResolverFactory(new DnsNameResolverProvider())
            .intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
                    .createScoped(SCOPE)))
            .build();
    mApi = SpeechGrpc.newStub(channel);

    // Schedule access token refresh before it expires
    if (mHandler != null) {
        mHandler.postDelayed(mFetchAccessTokenRunnable,
                Math.max(accessToken.getExpirationTime().getTime()
                        - System.currentTimeMillis()
                        - ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
    }
}
项目:undercarriage    文件:HelloWorldGrpcApplicationTests.java   
@Test
public void sayHelloEndpointReturnsExpectedResponse() {
    final String name = UUID.randomUUID().toString();

    final ManagedChannel channel = ManagedChannelBuilder
            .forAddress("localhost", applicationTestRule.application().port())
            .usePlaintext(true)
            .build();

    final GreeterGrpc.GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel);

    HelloRequest request = HelloRequest.newBuilder()
            .setName(name)
            .build();

    HelloResponse response = blockingStub.sayHello(request);

    assertThat(response.getMessage()).isEqualTo("Hello " + name);
}
项目:beam    文件:BeamFnControlClient.java   
public BeamFnControlClient(
    Endpoints.ApiServiceDescriptor apiServiceDescriptor,
    Function<Endpoints.ApiServiceDescriptor, ManagedChannel> channelFactory,
    BiFunction<
            StreamObserverClientFactory<InstructionRequest, BeamFnApi.InstructionResponse>,
            StreamObserver<BeamFnApi.InstructionRequest>,
            StreamObserver<BeamFnApi.InstructionResponse>>
        streamObserverFactory,
    EnumMap<
            BeamFnApi.InstructionRequest.RequestCase,
            ThrowingFunction<BeamFnApi.InstructionRequest, BeamFnApi.InstructionResponse.Builder>>
        handlers) {
  this.bufferedInstructions = new LinkedBlockingDeque<>();
  this.outboundObserver = streamObserverFactory.apply(
      BeamFnControlGrpc.newStub(channelFactory.apply(apiServiceDescriptor))::control,
      new InboundObserver());
  this.handlers = handlers;
  this.onFinish = new CompletableFuture<>();
}
项目:beam    文件:PubsubGrpcClient.java   
@Override
public PubsubClient newClient(
    @Nullable String timestampAttribute, @Nullable String idAttribute, PubsubOptions options)
    throws IOException {
  ManagedChannel channel = NettyChannelBuilder
      .forAddress(PUBSUB_ADDRESS, PUBSUB_PORT)
      .negotiationType(NegotiationType.TLS)
      .sslContext(GrpcSslContexts.forClient().ciphers(null).build())
      .build();

  return new PubsubGrpcClient(timestampAttribute,
                              idAttribute,
                              DEFAULT_TIMEOUT_S,
                              channel,
                              options.getGcpCredential());
}
项目:dropwizard-grpc    文件:GrpcServerTests.java   
@Test
public void createsPlainTextServer() throws Exception {
    final DropwizardTestSupport<TestConfiguration> testSupport =
            new DropwizardTestSupport<>(TestApplication.class, resourceFilePath("grpc-test-config.yaml"));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createPlaintextChannel(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        final GetPersonResponse resp =
                client.getPerson(GetPersonRequest.newBuilder().setName(TEST_PERSON_NAME).build());
        assertEquals(TEST_PERSON_NAME, resp.getPerson().getName());
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
项目:dropwizard-grpc    文件:GrpcServerTests.java   
@Test
public void createsServerWithTls() throws Exception {
    final DropwizardTestSupport<TestConfiguration> testSupport = new DropwizardTestSupport<>(TestApplication.class,
        resourceFilePath("grpc-test-config.yaml"), Optional.empty(),
        ConfigOverride.config("grpcServer.certChainFile", getURIForResource("cert/server.crt")),
        ConfigOverride.config("grpcServer.privateKeyFile", getURIForResource("cert/server.key")));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createClientChannelForEncryptedServer(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        final GetPersonResponse resp =
                client.getPerson(GetPersonRequest.newBuilder().setName(TEST_PERSON_NAME).build());
        assertEquals(TEST_PERSON_NAME, resp.getPerson().getName());
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
项目:dropwizard-grpc    文件:GrpcServerTests.java   
@Test
public void grpcServerGetsStopped() {
    final DropwizardTestSupport<TestConfiguration> testSupport =
            new DropwizardTestSupport<>(TestApplication.class, resourceFilePath("grpc-test-config.yaml"));

    ManagedChannel channel = null;
    try {
        testSupport.before();
        channel = createPlaintextChannel(testSupport);
        final PersonServiceGrpc.PersonServiceBlockingStub client = PersonServiceGrpc.newBlockingStub(channel);

        testSupport.after();

        try {
            // this should fail as the server is now stopped
            client.getPerson(GetPersonRequest.newBuilder().setName("blah").build());
            fail("Request should have failed.");
        } catch (final Exception e) {
            assertEquals(StatusRuntimeException.class, e.getClass());
            assertEquals(Code.UNAVAILABLE, ((StatusRuntimeException) e).getStatus().getCode());
        }
    } finally {
        testSupport.after();
        shutdownChannel(channel);
    }
}
项目:jahhan    文件:GrpcProtocol.java   
@SuppressWarnings("unchecked")
@Override
protected <T> T doRefer(Class<T> type, URL url) throws JahhanException {
    String name = type.getName();
    final ManagedChannel channel = ManagedChannelBuilder.forAddress(url.getHost(), url.getPort()).usePlaintext(true)
            .build();
    try {
        String substring = name.substring(name.lastIndexOf(".") + 1,
                name.indexOf(BaseConfiguration.INTERFACE_SUFFIX));
        String grpcImplName;
        if (name.startsWith(BaseConfiguration.SERVICE_PATH)) {
            grpcImplName = BaseConfiguration.SERVICE_PATH + packageName + substring + "GrpcInvoker";
        } else if (name.startsWith(BaseConfiguration.FRAMEWORK_PATH)) {
            grpcImplName =BaseConfiguration.FRAMEWORK_PATH + packageName + substring + "GrpcInvoker";
        } else {
            grpcImplName = "com" + packageName + substring + "GrpcInvoker";
        }
        Class<?> grpcImplClass = Class.forName(grpcImplName);
        GrpcAbstractInvoker newInstance = (GrpcAbstractInvoker) BaseContext.CTX.getInjector().getInstance(grpcImplClass);
        newInstance.setChannel(channel);
        return (T) newInstance;
    } catch (Exception e) {
        throw new JahhanException(e.getMessage(), e);
    }
}
项目:armeria    文件:ArmeriaGrpcServerInteropTest.java   
@Override
protected ManagedChannel createChannel() {
    try {
        final int port = server.getPort();
        return OkHttpChannelBuilder
                .forAddress("localhost", port)
                .negotiationType(NegotiationType.TLS)
                .maxInboundMessageSize(16 * 1024 * 1024)
                .connectionSpec(ConnectionSpec.MODERN_TLS)
                .overrideAuthority("example.com:" + port)
                .sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
                        Platform.get().getProvider(), ssc.certificate()))
                .build();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
项目:incubator-skywalking    文件:JVMMetricServiceHandlerTestCase.java   
public static void main(String[] args) {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 11800).usePlaintext(true).build();
    JVMMetricsServiceGrpc.JVMMetricsServiceBlockingStub blockingStub = JVMMetricsServiceGrpc.newBlockingStub(channel);

    JVMMetrics.Builder builder = JVMMetrics.newBuilder();
    builder.setApplicationInstanceId(2);

    JVMMetric.Builder metricBuilder = JVMMetric.newBuilder();
    metricBuilder.setTime(System.currentTimeMillis());

    buildCPUMetric(metricBuilder);
    buildGCMetric(metricBuilder);
    buildMemoryMetric(metricBuilder);
    buildMemoryPoolMetric(metricBuilder);

    builder.addMetrics(metricBuilder.build());

    blockingStub.collect(builder.build());
}
项目:utils-java    文件:GenomicsChannel.java   
private static ManagedChannel getGenomicsManagedChannel(List<ClientInterceptor> interceptors)
    throws SSLException {
  // Java 8's implementation of GCM ciphers is extremely slow. Therefore we disable
  // them here.
  List<String> defaultCiphers = GrpcSslContexts.forClient().ciphers(null).build().cipherSuites();
  List<String> performantCiphers = new ArrayList<>();
  for (String cipher : defaultCiphers) {
    if (!cipher.contains("GCM")) {
      performantCiphers.add(cipher);
    }
  }

  return NettyChannelBuilder.forAddress(GENOMICS_ENDPOINT, 443)
      .negotiationType(NegotiationType.TLS)
      .sslContext(GrpcSslContexts.forClient().ciphers(performantCiphers).build())
      .intercept(interceptors)
      .build();
}
项目:utils-java    文件:GenomicsStreamIterator.java   
/**
 * Create a stream iterator that will filter shard data using the predicate, if supplied.
 *
 * @param channel The channel.
 * @param request The request for the shard of data.
 * @param shardPredicate A predicate used to client-side filter results returned (e.g., enforce a
 *        shard boundary and/or limit to SNPs only) or null for no filtering.
 */

protected GenomicsStreamIterator(ManagedChannel channel, RequestT request,
    Predicate<ItemT> shardPredicate) {
  this.originalRequest = request;
  this.shardPredicate = shardPredicate;
  this.genomicsChannel = channel;
  stub = createStub(genomicsChannel);

  // Using default backoff settings. For details, see
  // https://developers.google.com/api-client-library/java/google-http-java-client/reference/1.19.0/com/google/api/client/util/ExponentialBackOff
  backoff = new ExponentialBackOff.Builder().build();

  // RETRY STATE: Initialize settings.
  delegate = createIterator(originalRequest);
  lastSuccessfulDataItem = null;
  idSentinel = null;
}