Java 类io.grpc.internal.DnsNameResolverProvider 实例源码

项目: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));
    }
}
项目: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));
    }
}
项目:appscode-login-plugin    文件:AppsCodeSecurityRealm.java   
private static LoadingCache<UserAuth, String> initCache() {
  try {
    currentAuth = ApprcHolder.get().currentAuth();
    URI uri = new URI(currentAuth.getApiserver());
    logger.info(String.format("Connecting to apiserver: %s  host: %s  port: %s",
        currentAuth.getApiserver(), uri.getHost(), uri.getPort()));
    NettyChannelBuilder builder = NettyChannelBuilder
        .forAddress(uri.getHost(), uri.getPort())
        .nameResolverFactory(new DnsNameResolverProvider());
    if (useTLS(currentAuth)) {
      File trustCertCollectionFile = null;
      builder
          .sslContext(GrpcSslContexts.forClient().trustManager(trustCertCollectionFile).build())
          .negotiationType(NegotiationType.TLS);
    } else {
      builder.negotiationType(NegotiationType.PLAINTEXT);
    }
    channel = builder.build();
    return CacheBuilder.newBuilder()
        .expireAfterAccess(DESCRIPTOR.getAuthCacheTtl(), TimeUnit.SECONDS)
        .build(
            new CacheLoader<UserAuth, String>() {
              @Override
              public String load(UserAuth key) throws Exception {
                if (isToken(key.getSecret())) {
                  return checkToken(key.getUsername(),
                      key.getSecret().substring(BEARER_PREFIX.length()));
                }
                return checkPassword(key.getUsername(), key.getSecret());
              }
            }
        );
  } catch (URISyntaxException | SSLException e) {
    logger.log(Level.SEVERE, e.getMessage());
  }
  return null;
}
项目:grpc-java-by-example    文件:ClientSideLoadBalancedEchoClient.java   
public static void main(String[] args) throws InterruptedException, UnknownHostException {
  String target = System.getenv("ECHO_SERVICE_TARGET");
  if (target == null || target.isEmpty()) {
    target = "localhost:8080";
  }
  final ManagedChannel channel = ManagedChannelBuilder.forTarget(target)
      .nameResolverFactory(new DnsNameResolverProvider())  // this is on by default
      .loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
      .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));
      }
    });
  }
}
项目:incubator-skywalking    文件:GRPCChannelManager.java   
@Override
public void run() {
    logger.debug("Selected collector grpc service running, reconnect:{}.", reconnect);
    if (reconnect) {
        if (RemoteDownstreamConfig.Collector.GRPC_SERVERS.size() > 0) {
            String server = "";
            try {
                int index = Math.abs(random.nextInt()) % RemoteDownstreamConfig.Collector.GRPC_SERVERS.size();
                server = RemoteDownstreamConfig.Collector.GRPC_SERVERS.get(index);
                String[] ipAndPort = server.split(":");
                ManagedChannelBuilder<?> channelBuilder =
                    NettyChannelBuilder.forAddress(ipAndPort[0], Integer.parseInt(ipAndPort[1]))
                        .nameResolverFactory(new DnsNameResolverProvider())
                        .maxInboundMessageSize(1024 * 1024 * 50)
                        .usePlaintext(true);
                managedChannel = channelBuilder.build();
                if (!managedChannel.isShutdown() && !managedChannel.isTerminated()) {
                    reconnect = false;
                    notify(GRPCChannelStatus.CONNECTED);
                } else {
                    notify(GRPCChannelStatus.DISCONNECT);
                }
                return;
            } catch (Throwable t) {
                logger.error(t, "Create channel to {} fail.", server);
                notify(GRPCChannelStatus.DISCONNECT);
            }
        }

        logger.debug("Selected collector grpc service is not available. Wait {} seconds to retry", Config.Collector.GRPC_CHANNEL_CHECK_INTERVAL);
    }
}
项目:incubator-skywalking    文件:GRPCNoServerTest.java   
public static void main(String[] args) throws InterruptedException {
    ManagedChannelBuilder<?> channelBuilder =
        NettyChannelBuilder.forAddress("127.0.0.1", 8080)
            .nameResolverFactory(new DnsNameResolverProvider())
            .maxInboundMessageSize(1024 * 1024 * 50)
            .usePlaintext(true);
    ManagedChannel channel = channelBuilder.build();
    TraceSegmentServiceGrpc.TraceSegmentServiceStub serviceStub = TraceSegmentServiceGrpc.newStub(channel);
    final Status[] status = {null};
    StreamObserver<UpstreamSegment> streamObserver = serviceStub.collect(new StreamObserver<Downstream>() {
        @Override public void onNext(Downstream value) {

        }

        @Override public void onError(Throwable t) {
            status[0] = ((StatusRuntimeException)t).getStatus();
        }

        @Override public void onCompleted() {

        }
    });

    streamObserver.onNext(null);
    streamObserver.onCompleted();

    Thread.sleep(2 * 1000);

    Assert.assertEquals(status[0].getCode(), Status.UNAVAILABLE.getCode());
}
项目:onos    文件:GnmiDeviceDescriptionDiscovery.java   
/**
 * Obtains the ManagedChannel to be used for the communication.
 *
 * @return the managed channel
 */
private ManagedChannel getChannel(String serverAddr, String serverPortString) {

    DeviceId deviceId = handler().data().deviceId();

    GrpcController controller = handler().get(GrpcController.class);
    ManagedChannel channel = null;

    //FIXME can be optimized
    //getting a channel if exists.
    ManagedChannel managedChannel = controller
            .getChannels(handler().data().deviceId()).stream().filter(c -> {
                String[] authority = c.authority().split(":");
                String host = authority[0];
                String port = authority[1];
                return host.equals(serverAddr) && port.equals(serverPortString);
            }).findAny().orElse(null);

    if (managedChannel != null) {
        log.debug("Reusing Channel");
        channel = managedChannel;
    } else {
        log.debug("Creating Channel");
        GrpcChannelId newChannelId = GrpcChannelId.of(deviceId, "gnmi");

        ManagedChannelBuilder channelBuilder = NettyChannelBuilder
                .forAddress(serverAddr, Integer.valueOf(serverPortString))
                .usePlaintext(true)
                .nameResolverFactory(new DnsNameResolverProvider());

        try {
            channel = controller.connectChannel(newChannelId, channelBuilder);
        } catch (IOException e) {
            log.warn("Unable to connect to gRPC server of {}: {}",
                    deviceId, e.getMessage());
        }
    }
    return channel;
}
项目:onos    文件:GrpcRemoteServiceProvider.java   
private ManagedChannel createChannel(URI uri) {
    log.debug("Creating channel for {}", uri);
    int port = GrpcRemoteServiceServer.DEFAULT_LISTEN_PORT;
    if (uri.getPort() != -1) {
        port = uri.getPort();
    }
    return NettyChannelBuilder.forAddress(uri.getHost(), port)
            .negotiationType(NegotiationType.PLAINTEXT)
            // TODO Not ideal fix, gRPC discovers name resolvers
            // in the class path, but OSGi was preventing it.
            // Manually specifying the default dns resolver for now.
            .nameResolverFactory(new DnsNameResolverProvider())
            .build();
}
项目:grpc-java    文件:NameResolverProviderTest.java   
@Test
public void baseProviders() {
  List<NameResolverProvider> providers = NameResolverProvider.providers();
  assertEquals(1, providers.size());
  assertSame(DnsNameResolverProvider.class, providers.get(0).getClass());
  assertEquals("dns", NameResolverProvider.asFactory().getDefaultScheme());
}