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


Java ManagedChannel類代碼示例

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


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

示例1: connectPlugin

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

示例2: startServer

import io.grpc.ManagedChannel; //導入依賴的package包/類
@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));
                                }
                            }
                        });
                
            }
        });
}
 
開發者ID:aksalj,項目名稱:africastalking-java,代碼行數:40,代碼來源:ATServerTest.java

示例3: main

import io.grpc.ManagedChannel; //導入依賴的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

示例4: getGenomicsManagedChannel

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

示例5: fetchToken

import io.grpc.ManagedChannel; //導入依賴的package包/類
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;
    }
 
開發者ID:aksalj,項目名稱:africastalking-android,代碼行數:20,代碼來源:Service.java

示例6: GrpcClientMessageSender

import io.grpc.ManagedChannel; //導入依賴的package包/類
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());
}
 
開發者ID:apache,項目名稱:incubator-servicecomb-saga,代碼行數:17,代碼來源:GrpcClientMessageSender.java

示例7: build

import io.grpc.ManagedChannel; //導入依賴的package包/類
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);
        }
 
開發者ID:ExpediaDotCom,項目名稱:haystack-client-java,代碼行數:18,代碼來源:GRPCAgentClient.java

示例8: getChannel

import io.grpc.ManagedChannel; //導入依賴的package包/類
/**
 * @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();
}
 
開發者ID:silentbalanceyh,項目名稱:vertx-zero,代碼行數:30,代碼來源:RpcSslTool.java

示例9: send

import io.grpc.ManagedChannel; //導入依賴的package包/類
@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;
}
 
開發者ID:silentbalanceyh,項目名稱:vertx-zero,代碼行數:18,代碼來源:UnitySpear.java

示例10: AssistantClient

import io.grpc.ManagedChannel; //導入依賴的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

示例11: greet

import io.grpc.ManagedChannel; //導入依賴的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

示例12: onDestroy

import io.grpc.ManagedChannel; //導入依賴的package包/類
@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;
    }
}
 
開發者ID:hsavaliya,項目名稱:GoogleAssistantSDK,代碼行數:19,代碼來源:SpeechService.java

示例13: fetchAccessToken

import io.grpc.ManagedChannel; //導入依賴的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

示例14: createLeaderWrapper

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

示例15: create

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


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