當前位置: 首頁>>代碼示例>>Java>>正文


Java ManagedChannelBuilder類代碼示例

本文整理匯總了Java中io.grpc.ManagedChannelBuilder的典型用法代碼示例。如果您正苦於以下問題:Java ManagedChannelBuilder類的具體用法?Java ManagedChannelBuilder怎麽用?Java ManagedChannelBuilder使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ManagedChannelBuilder類屬於io.grpc包,在下文中一共展示了ManagedChannelBuilder類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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();
    }
 
開發者ID:meteatamel,項目名稱:grpc-samples-java,代碼行數:27,代碼來源:GreeterClient.java

示例2: AssistantClient

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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);
}
 
開發者ID:mautini,項目名稱:google-assistant-java-demo,代碼行數:18,代碼來源:AssistantClient.java

示例3: greet

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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();
            }
        }
    }
 
開發者ID:imrenagi,項目名稱:microservice-skeleton,代碼行數:27,代碼來源:GreeterServiceConsumer.java

示例4: fetchAccessToken

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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();

        }

    }
 
開發者ID:hsavaliya,項目名稱:GoogleAssistantSDK,代碼行數:20,代碼來源:SpeechService.java

示例5: getChannel

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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;
}
 
開發者ID:pingcap,項目名稱:tikv-client-lib-java,代碼行數:22,代碼來源:TiSession.java

示例6: getMessage

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
@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();
    }
}
 
開發者ID:moensun,項目名稱:ms-grpc,代碼行數:18,代碼來源:GreetTest.java

示例7: main

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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);
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:25,代碼來源:TimeClient.java

示例8: serverRunsAndRespondsCorrectly

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
@Test
public void serverRunsAndRespondsCorrectly() throws ExecutionException,
        IOException,
        InterruptedException,
        TimeoutException {
    final String name = UUID.randomUUID().toString();

    Server server = ServerBuilder.forPort(9999)
            .addService(new GreeterImpl())
            .build();

    server.start();

    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort())
            .usePlaintext(true)
            .build();

    GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel);

    CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build());

    await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name));

    channel.shutdown();
    channel.awaitTermination(1, TimeUnit.MINUTES);
    channel.shutdownNow();

    server.shutdown();
    server.awaitTermination(1, TimeUnit.MINUTES);
    server.shutdownNow();
}
 
開發者ID:salesforce,項目名稱:grpc-java-contrib,代碼行數:32,代碼來源:CompletableFutureEndToEndTest.java

示例9: SeldonClientExample

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
/** Construct client for accessing RouteGuide server using the existing channel. */
public SeldonClientExample(ManagedChannelBuilder<?> channelBuilder) {
 ClientInterceptor interceptor = new HeaderClientInterceptor();
  channel = channelBuilder.build();
  Channel interceptChannel = ClientInterceptors.intercept(channel, interceptor);
  blockingStub = SeldonGrpc.newBlockingStub(interceptChannel);
  asyncStub = SeldonGrpc.newStub(interceptChannel);
}
 
開發者ID:SeldonIO,項目名稱:seldon-core,代碼行數:9,代碼來源:SeldonClientExample.java

示例10: getChannel

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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;
		}
	}
	
}
 
開發者ID:laddcn,項目名稱:grpcx,代碼行數:22,代碼來源:ChannelFactory.java

示例11: rollbackConfig

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
/**
 * 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;
        }
    }
}
 
開發者ID:actiontech,項目名稱:dble,代碼行數:27,代碼來源:AlarmAppender.java

示例12: defaultChannelBuilder

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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;
}
 
開發者ID:coreos,項目名稱:jetcd,代碼行數:27,代碼來源:ClientConnectionManager.java

示例13: ClientApp

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:SpineEventEngine,項目名稱:examples-java,代碼行數:23,代碼來源:ClientApp.java

示例14: beforeClass

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
@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);
}
 
開發者ID:edipermadi,項目名稱:bohpien-hsm-service,代碼行數:20,代碼來源:DigestTest.java

示例15: main

import io.grpc.ManagedChannelBuilder; //導入依賴的package包/類
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));
      }
    });
  }
}
 
開發者ID:saturnism,項目名稱:grpc-java-by-example,代碼行數:25,代碼來源:SimpleEchoClient.java


注:本文中的io.grpc.ManagedChannelBuilder類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。