类io.grpc.util.RoundRobinLoadBalancerFactory源码实例Demo

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

@Inject
public DefaultCellConnector(CellInfoResolver cellInfoResolver) {
    List<Cell> cells = cellInfoResolver.resolve();

    if (cells != null && !cells.isEmpty()) {
        channels = cells.stream()
                .collect(Collectors.toMap(
                        cell -> cell,
                        cell -> NettyChannelBuilder.forTarget(cell.getAddress())
                                .usePlaintext(true)
                                .loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
                                .build()
                ));
    } else {
        channels = Collections.emptyMap();
    }
}
 
@Override
public Channel createChannel(String name) {
  RoundRobinLoadBalancerFactory instance = RoundRobinLoadBalancerFactory.getInstance();
  ManagedChannelBuilder builder = ManagedChannelBuilder.forTarget("spring://" + name)
          .nameResolverFactory(new DiscoveryClientResolverFactory(client))
	.loadBalancerFactory(instance);

  if (channels.getChannels().containsKey(name)) {
    if (channels.getChannels().get(name).isPlaintext()) {
       builder.usePlaintext();
    }
  } else {
    builder.usePlaintext();
  }

  return builder.build();
}
 
private ManagedChannel getTitusGrpcChannel() {
    return NettyChannelBuilder.forAddress(titusApiHost, titusApiPort)
            .loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
            .keepAliveTime(GRPC_KEEP_ALIVE_TIME, TimeUnit.SECONDS)
            .keepAliveTimeout(GRPC_KEEP_ALIVE_TIMEOUT, TimeUnit.SECONDS)
            .userAgent(GRPC_CLIENT_AGENT)
            .usePlaintext(true)
            .build();
}
 
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 KubernetesNameResolverProvider())  // 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));
      }
    });
  }
}
 
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));
      }
    });
  }
}
 
@ConditionalOnMissingBean
@Bean
public LoadBalancer.Factory defaultGrpcLoadBalancerFactory() {
	return RoundRobinLoadBalancerFactory.getInstance();
}
 
源代码7 项目: glowroot   文件: CentralConnection.java
CentralConnection(String collectorAddress, @Nullable String collectorAuthority,
        List<File> confDirs, AtomicBoolean inConnectionFailure) throws SSLException {
    ParsedCollectorAddress parsedCollectorAddress = parseCollectorAddress(collectorAddress);
    eventLoopGroup = EventLoopGroups.create("Glowroot-GRPC-Worker-ELG");
    channelExecutor =
            Executors.newSingleThreadExecutor(ThreadFactories.create("Glowroot-GRPC-Executor"));
    NettyChannelBuilder builder;
    if (parsedCollectorAddress.targets().size() == 1) {
        CollectorTarget target = parsedCollectorAddress.targets().get(0);
        builder = NettyChannelBuilder.forAddress(target.host(), target.port());
        if (collectorAuthority != null) {
            builder.overrideAuthority(collectorAuthority);
        }
    } else {
        // this connection mechanism may be deprecated in the future in favor resolving a single
        // address to multiple collectors via DNS (above)
        String authority;
        if (collectorAuthority != null) {
            authority = collectorAuthority;
        } else if (!parsedCollectorAddress.https()) {
            authority = "dummy-service-authority";
        } else {
            throw new IllegalStateException("collector.authority is required when connecting"
                    + " over HTTPS to a comma-separated list of glowroot central collectors");
        }
        builder = NettyChannelBuilder.forTarget("dummy-target")
                .nameResolverFactory(new MultipleAddressNameResolverFactory(
                        parsedCollectorAddress.targets(), authority));
    }
    // single address may resolve to multiple collectors above via DNS, so need to specify round
    // robin here even if only single address (first part of conditional above)
    builder.loadBalancerFactory(RoundRobinLoadBalancerFactory.getInstance())
            .eventLoopGroup(eventLoopGroup)
            .executor(channelExecutor)
            // aggressive keep alive, shouldn't even be used since gauge data is sent every
            // 5 seconds and keep alive will only kick in after 10 seconds of not hearing back
            // from the server
            .keepAliveTime(10, SECONDS);
    if (parsedCollectorAddress.https()) {
        SslContextBuilder sslContext = GrpcSslContexts.forClient();
        File trustCertCollectionFile = getTrustCertCollectionFile(confDirs);
        if (trustCertCollectionFile != null) {
            sslContext.trustManager(trustCertCollectionFile);
        }
        channel = builder.sslContext(sslContext.build())
                .negotiationType(NegotiationType.TLS)
                .build();
    } else {
        channel = builder.negotiationType(NegotiationType.PLAINTEXT)
                .build();
    }
    retryExecutor = Executors.newSingleThreadScheduledExecutor(
            ThreadFactories.create("Glowroot-Collector-Retry"));
    this.inConnectionFailure = inConnectionFailure;
    this.collectorAddress = collectorAddress;
}
 
 类所在包
 同包方法