Java 类io.grpc.ManagedChannelBuilder 实例源码

项目: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();
    }
项目: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   
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    文件: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;
}
项目: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();
    }
}
项目:grpc-java-contrib    文件:TimeClient.java   
public static void main(String[] args) throws Exception {
    String host = args[0];
    int port = Integer.parseInt(args[1]);

    String abstractName = "mesh://timeService";

    // Open a channel to the server
    Channel channel = ManagedChannelBuilder
            .forTarget(abstractName)
            .nameResolverFactory(StaticResolver.factory(new InetSocketAddress(host, port)))
            .usePlaintext(true)
            .build();

    // Create a CompletableFuture-based stub
    TimeServiceGrpc8.TimeServiceCompletableFutureStub stub = TimeServiceGrpc8.newCompletableFutureStub(channel);

    // Call the service
    CompletableFuture<TimeReply> completableFuture = stub.getTime(Empty.getDefaultInstance());
    TimeReply timeReply = completableFuture.get();

    // Convert to JDK8 types
    Instant now = MoreTimestamps.toInstantUtc(timeReply.getTime());
    System.out.println("The time is " + now);
}
项目: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;
        }
    }

}
项目:dble    文件:AlarmAppender.java   
/**
 * if the config is rollback the config of dbleAppender should be rollback too
 */
public static void rollbackConfig() {
    if (stub == null && (grpcUrlOld == null && "".equals(grpcUrlOld))) {
        grpcUrl = grpcUrlOld;
        serverId = serverIdOld;
        alertComponentId = alertComponentIdOld;
        port = portOld;
        grpcUrl = grpcUrlOld;
        grpcLevel = grpcLevelOld;
        return;
    } else {
        grpcUrl = grpcUrlOld;
        serverId = serverIdOld;
        alertComponentId = alertComponentIdOld;
        port = portOld;
        grpcUrl = grpcUrlOld;
        try {
            Channel channel = ManagedChannelBuilder.forAddress(grpcUrl, port).usePlaintext(true).build();
            stub = UcoreGrpc.newBlockingStub(channel);
        } catch (Exception e) {
            return;
        }
    }
}
项目:jetcd    文件:ClientConnectionManager.java   
private ManagedChannelBuilder<?> defaultChannelBuilder() {
  NettyChannelBuilder channelBuilder = NettyChannelBuilder.forTarget("etcd");

  if (builder.sslContext() != null) {
    channelBuilder.sslContext(builder.sslContext());
  } else {
    channelBuilder.usePlaintext(true);
  }

  channelBuilder.nameResolverFactory(
      forEndpoints(
        Optional.ofNullable(builder.authority()).orElse("etcd"),
        builder.endpoints(),
        Optional.ofNullable(builder.uriResolverLoader())
            .orElseGet(URIResolverLoader::defaultLoader)
      )
  );

  if (builder.loadBalancerFactory() != null) {
    channelBuilder.loadBalancerFactory(builder.loadBalancerFactory());
  }

  channelBuilder.intercept(new AuthTokenInterceptor());

  return channelBuilder;
}
项目:examples-java    文件:ClientApp.java   
/**
 * Construct the client connecting to server at {@code host:port}.
 */
public ClientApp(String host, int port) {
    final TypeUrl orderTypeUrl = TypeUrl.from(Order.getDescriptor());
    final Target.Builder target = Target.newBuilder()
                                        .setType(orderTypeUrl.getTypeName());
    orderTopic = Topic.newBuilder()
                      .setTarget(target)
                      .build();

    commandFactory = CommandFactory.newBuilder()
                                   .setActor(newUserId(Identifiers.newUuid()))
                                   .setZoneOffset(ZoneOffsets.UTC)
                                   .build();
    channel = ManagedChannelBuilder
            .forAddress(host, port)
            .usePlaintext(true)
            .build();
    blockingClient = CommandServiceGrpc.newBlockingStub(channel);
    nonBlockingClient = SubscriptionServiceGrpc.newStub(channel);
}
项目:bohpien-hsm-service    文件:DigestTest.java   
@BeforeClass
public void beforeClass() throws IOException, DuplicateSessionException {
    /* create and start service */
    final int port = 8080;
    final ServiceRunner service = new ServiceRunner.Builder()
            .setSessionProvider(sessionProvider)
            .setPort(port)
            .build();
    thread = new Thread(service);
    thread.start();

    /* create client */
    final Channel channel = ManagedChannelBuilder.forAddress("127.0.0.1", port)
            .usePlaintext(true).build();
    client = DigestServiceGrpc.newBlockingStub(channel);

    /* register session id */
    sessionId = sessionProvider.createSession(userId);
}
项目: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);
                }
            });
}
项目:javatrove    文件:ChatClientImpl.java   
@Override
public void login(String host, int port, String name) {
    channel = ManagedChannelBuilder.forAddress(host, port)
        .usePlaintext(true)
        .build();

    blockingStub = ChatGrpc.newBlockingStub(channel);
    asyncStub = ChatGrpc.newStub(channel);

    id = toSHA1(InetAddress.getLoopbackAddress().getHostName() + "-" + System.nanoTime());
    asyncStub.login(Login.newBuilder()
            .setName(name)
            .setId(id)
            .build(),
        new StreamObserverAdapter<Response>() {
            @Override
            public void onNext(Response value) {
                clientDispatcher.dispatch(asCommand(value));
            }

            @Override
            public void onError(Throwable throwable) {
                eventBus.publishAsync(new ThrowableEvent(throwable));
            }
        });
}
项目:grpc_greetertimer    文件:GreeterTimerServer.java   
/** Construct client connecting to HelloWorld server at {@code host:port}. */
BatchGreeterClient(TimerRequest request, StreamObserver<BatchResponse> observer) {
  Preconditions.checkNotNull(request, "request required");
  Preconditions.checkNotNull(observer, "response observer required");
  Preconditions.checkArgument(request.getHost().length() > 0, "hostname required");
  Preconditions.checkArgument(request.getPort() > 0, "grpc port required");
  Preconditions.checkArgument(port > 0, "grpc port must be greater than zero");
  Preconditions.checkArgument(
      request.getTotalSize() > 0, "total request count must be greater than zero");
  Preconditions.checkArgument(
      request.getBatchSize() > 0, "batch request size must be greater than zero");

  this.request = request;
  this.observer = observer;

  this.channel =
      ManagedChannelBuilder.forAddress(request.getHost(), request.getPort())
          .usePlaintext(true)
          .build();

  this.blockingStub = GreeterGrpc.newBlockingStub(channel);
}
项目:thingsboard    文件:RpcSessionActor.java   
private void initSession(RpcSessionCreateRequestMsg msg) {
    log.info("[{}] Initializing session", context().self());
    ServerAddress remoteServer = msg.getRemoteAddress();
    listener = new BasicRpcSessionListener(systemContext, context().parent(), context().self());
    if (msg.getRemoteAddress() == null) {
        // Server session
        session = new GrpcSession(listener);
        session.setOutputStream(msg.getResponseObserver());
        session.initInputStream();
        session.initOutputStream();
        systemContext.getRpcService().onSessionCreated(msg.getMsgUid(), session.getInputStream());
    } else {
        // Client session
        Channel channel = ManagedChannelBuilder.forAddress(remoteServer.getHost(), remoteServer.getPort()).usePlaintext(true).build();
        session = new GrpcSession(remoteServer, listener);
        session.initInputStream();

        ClusterRpcServiceGrpc.ClusterRpcServiceStub stub = ClusterRpcServiceGrpc.newStub(channel);
        StreamObserver<ClusterAPIProtos.ToRpcServerMessage> outputStream = stub.handlePluginMsgs(session.getInputStream());

        session.setOutputStream(outputStream);
        session.initOutputStream();
        outputStream.onNext(toConnectMsg());
    }
}
项目: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);
}
项目: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);
    }
}
项目: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());
}
项目:lumongo    文件:LumongoConnection.java   
public void open(boolean compressedConnection) throws IOException {

        ManagedChannelBuilder<?> managedChannelBuilder = ManagedChannelBuilder.forAddress(member.getServerAddress(), member.getExternalPort())
                .maxInboundMessageSize(256 * 1024 * 1024).usePlaintext(true);
        channel = managedChannelBuilder.build();

        blockingStub = ExternalServiceGrpc.newBlockingStub(channel);
        if (compressedConnection) {
            blockingStub = blockingStub.withCompression("gzip");
        }

        asyncStub = ExternalServiceGrpc.newStub(channel);
        if (compressedConnection) {
            asyncStub = asyncStub.withCompression("gzip");
        }

        System.err.println("INFO: Connecting to <" + member.getServerAddress() + ">");

    }
项目:onos    文件:AbstractP4RuntimeHandlerBehaviour.java   
/**
 * Create a P4Runtime client for this device. Returns true if the operation was successful, false otherwise.
 *
 * @return true if successful, false otherwise
 */
protected boolean createClient() {
    deviceId = handler().data().deviceId();
    controller = handler().get(P4RuntimeController.class);

    String serverAddr = this.data().value(P4RUNTIME_SERVER_ADDR_KEY);
    String serverPortString = this.data().value(P4RUNTIME_SERVER_PORT_KEY);
    String p4DeviceIdString = this.data().value(P4RUNTIME_DEVICE_ID_KEY);

    if (serverAddr == null || serverPortString == null || p4DeviceIdString == null) {
        log.warn("Unable to create client for {}, missing driver data key (required is {}, {}, and {})",
                 deviceId, P4RUNTIME_SERVER_ADDR_KEY, P4RUNTIME_SERVER_PORT_KEY, P4RUNTIME_DEVICE_ID_KEY);
        return false;
    }

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

    if (!controller.createClient(deviceId, Long.parseUnsignedLong(p4DeviceIdString), channelBuilder)) {
        log.warn("Unable to create client for {}, aborting operation", deviceId);
        return false;
    }

    return true;
}
项目:onos    文件:P4RuntimeControllerImpl.java   
@Override
public boolean createClient(DeviceId deviceId, long p4DeviceId, ManagedChannelBuilder channelBuilder) {
    checkNotNull(deviceId);
    checkNotNull(channelBuilder);

    deviceLocks.getUnchecked(deviceId).writeLock().lock();
    log.info("Creating client for {} (with internal device id {})...", deviceId, p4DeviceId);

    try {
        if (clients.containsKey(deviceId)) {
            throw new IllegalStateException(format("A client already exists for %s", deviceId));
        } else {
            return doCreateClient(deviceId, p4DeviceId, channelBuilder);
        }
    } finally {
        deviceLocks.getUnchecked(deviceId).writeLock().unlock();
    }
}
项目:onos    文件:P4RuntimeControllerImpl.java   
private boolean doCreateClient(DeviceId deviceId, long p4DeviceId, ManagedChannelBuilder channelBuilder) {

        GrpcChannelId channelId = GrpcChannelId.of(deviceId, "p4runtime");

        // Channel defaults.
        channelBuilder.nameResolverFactory(nameResolverProvider);

        ManagedChannel channel;
        try {
            channel = grpcController.connectChannel(channelId, channelBuilder);
        } catch (IOException e) {
            log.warn("Unable to connect to gRPC server of {}: {}", deviceId, e.getMessage());
            return false;
        }

        P4RuntimeClient client = new P4RuntimeClientImpl(deviceId, p4DeviceId, channel, this);

        channelIds.put(deviceId, channelId);
        clients.put(deviceId, client);

        return true;
    }
项目:onos    文件:GrpcControllerImpl.java   
@Override
public ManagedChannel connectChannel(GrpcChannelId channelId,
                                     ManagedChannelBuilder<?> channelBuilder)
        throws IOException {
    checkNotNull(channelId);
    checkNotNull(channelBuilder);

    Lock lock = channelLocks.computeIfAbsent(channelId, k -> new ReentrantLock());
    lock.lock();

    try {
        if (enableMessageLog) {
            channelBuilder.intercept(new InternalLogChannelInterceptor(channelId));
        }
        ManagedChannel channel = channelBuilder.build();
        // Forced connection not yet implemented. Use workaround...
        // channel.getState(true);
        doDummyMessage(channel);
        channels.put(channelId, channel);
        return channel;
    } finally {
        lock.unlock();
    }
}
项目:grpc-java    文件:OkHttpClientInteropServlet.java   
@Override
protected ManagedChannel createChannel() {
  assertEquals(
      "jdk7 required",
      "1.7",
      System.getProperty("java.specification.version"));
  assertEquals(
      "Can not run in dev servers because they lack org.conscrypt.OpenSSLProvider support",
      "Production",
      System.getProperty("com.google.appengine.runtime.environment"));
  ManagedChannelBuilder<?> builder =
      ManagedChannelBuilder.forTarget(INTEROP_TEST_ADDRESS)
          .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE);
  assertTrue(builder instanceof OkHttpChannelBuilder);
  return builder.build();
}
项目:grpc-java    文件:ErrorHandlingClient.java   
void run() throws Exception {
  // Port 0 means that the operating system will pick an available port to use.
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      responseObserver.onError(Status.INTERNAL
          .withDescription("Eggplant Xerxes Crybaby Overbite Narwhal").asRuntimeException());
    }
  }).build().start();
  channel =
      ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext(true).build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
项目:grpc-java    文件:DetailErrorSample.java   
void run() throws Exception {
  Server server = ServerBuilder.forPort(0).addService(new GreeterGrpc.GreeterImplBase() {
    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
      Metadata trailers = new Metadata();
      trailers.put(DEBUG_INFO_TRAILER_KEY, DEBUG_INFO);
      responseObserver.onError(Status.INTERNAL.withDescription(DEBUG_DESC)
          .asRuntimeException(trailers));
    }
  }).build().start();
  channel =
      ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext(true).build();

  blockingCall();
  futureCallDirect();
  futureCallCallback();
  asyncCall();
  advancedAsyncCall();

  channel.shutdown();
  server.shutdown();
  channel.awaitTermination(1, TimeUnit.SECONDS);
  server.awaitTermination();
}
项目:grpc-java    文件:HelloworldActivity.java   
@Override
protected String doInBackground(String... params) {
  String host = params[0];
  String message = params[1];
  String portStr = params[2];
  int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr);
  try {
    channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
    GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName(message).build();
    HelloReply reply = stub.sayHello(request);
    return reply.getMessage();
  } catch (Exception e) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    return String.format("Failed... : %n%s", sw);
  }
}
项目:grpc-java    文件:TesterOkHttpChannelBuilder.java   
public static ManagedChannel build(String host, int port, @Nullable String serverHostOverride,
    boolean useTls, @Nullable InputStream testCa, @Nullable String androidSocketFactoryTls) {
  ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
      .maxInboundMessageSize(16 * 1024 * 1024);
  if (serverHostOverride != null) {
    // Force the hostname to match the cert the server uses.
    channelBuilder.overrideAuthority(serverHostOverride);
  }
  if (useTls) {
    try {
      SSLSocketFactory factory;
      if (androidSocketFactoryTls != null) {
        factory = getSslCertificateSocketFactory(testCa, androidSocketFactoryTls);
      } else {
        factory = getSslSocketFactory(testCa);
      }
      ((OkHttpChannelBuilder) channelBuilder).negotiationType(NegotiationType.TLS);
      ((OkHttpChannelBuilder) channelBuilder).sslSocketFactory(factory);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  } else {
    channelBuilder.usePlaintext(true);
  }
  return channelBuilder.build();
}
项目:muckery    文件:GrpcTest.java   
@Before
public void setUp() throws Exception {

    final int port = NetUtil.findUnusedPort();
    this.server = ServerBuilder.forPort(port)
                               .executor(this.exec)
                               .addService(new HelloService())
                               .build()
                               .start();


    this.channel = ManagedChannelBuilder.forAddress("127.0.0.1", port)
                                        .executor(this.exec)
                                        .usePlaintext(true)
                                        .build();
}
项目:neo_grpc    文件:Neo4jGRPCBenchmark.java   
@Setup(Level.Trial)
public void prepare() throws Exception {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9999)
            // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
            // needing certificates.
            .usePlaintext(true)
            .build();
    blockingStub = Neo4jQueryGrpc.newBlockingStub(channel);

    driver = GraphDatabase.driver( "bolt://localhost:7687", AuthTokens.basic( "neo4j", "swordfish" ) );
}
项目:neo_grpc    文件:Neo4jGRPCServiceTest.java   
@Before
public void setup() throws Exception {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 9999)
            // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
            // needing certificates.
            .usePlaintext(true)
            .build();
    blockingStub = Neo4jQueryGrpc.newBlockingStub(channel);
}
项目:rejoiner    文件:HelloWorldClientModule.java   
@Override
protected void configure() {
  ManagedChannel channel =
      ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build();
  bind(StreamingGreeterGrpc.StreamingGreeterStub.class)
      .toInstance(StreamingGreeterGrpc.newStub(channel));
}
项目:rejoiner    文件:BookClientModule.java   
@Override
protected void configure() {
  ManagedChannel channel =
      ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build();
  bind(BookServiceGrpc.BookServiceFutureStub.class)
      .toInstance(BookServiceGrpc.newFutureStub(channel));
  bind(BookServiceGrpc.BookServiceBlockingStub.class)
      .toInstance(BookServiceGrpc.newBlockingStub(channel));
}
项目:rejoiner    文件:ShelfClientModule.java   
@Override
protected void configure() {
  ManagedChannel channel =
      ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext(true).build();
  bind(ShelfServiceGrpc.ShelfServiceFutureStub.class)
      .toInstance(ShelfServiceGrpc.newFutureStub(channel));
  bind(ShelfServiceGrpc.ShelfServiceBlockingStub.class)
      .toInstance(ShelfServiceGrpc.newBlockingStub(channel));
}
项目:incubator-servicecomb-saga    文件:LoadBalancedClusterMessageSender.java   
public LoadBalancedClusterMessageSender(String[] addresses,
    MessageSerializer serializer,
    MessageDeserializer deserializer,
    ServiceConfig serviceConfig,
    MessageHandler handler,
    int reconnectDelay) {

  if (addresses.length == 0) {
    throw new IllegalArgumentException("No reachable cluster address provided");
  }

  channels = new ArrayList<>(addresses.length);
  for (String address : addresses) {
    ManagedChannel channel = ManagedChannelBuilder.forTarget(address)
        .usePlaintext(true)
        .build();

    channels.add(channel);
    senders.put(
        new GrpcClientMessageSender(
            address,
            channel,
            serializer,
            deserializer,
            serviceConfig,
            errorHandlerFactory(),
            handler),
        0L);
  }

  scheduleReconnectTask(reconnectDelay);
}
项目:paraflow    文件:MetaClient.java   
public MetaClient(String host, int port)
{
    this(ManagedChannelBuilder.forAddress(host, port)
            // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
            // needing certificates.
            .usePlaintext(true)
            .build());
}
项目:spring-remoting-grpc    文件:GrpcInvokerProxyFactoryBean.java   
@Override
public void afterPropertiesSet() {
    super.afterPropertiesSet();
    if (getServiceInterface() == null) {
        throw new IllegalArgumentException("Property 'serviceInterface' is required");
    }
    this.serviceProxy = new ProxyFactory(getServiceInterface(), this).getProxy(getBeanClassLoader());
    channel = ManagedChannelBuilder.forTarget(getServiceUrl()).usePlaintext(true).build();
    remotingServiceBlockingStub = RemotingServiceGrpc.newBlockingStub(channel);
}