本文整理汇总了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);
}
示例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));
}
}
});
}
});
}
示例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();
}
示例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();
}
示例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;
}
示例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());
}
示例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);
}
示例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();
}
示例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;
}
示例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);
}
示例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();
}
}
}
示例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;
}
}
示例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();
}
}
示例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;
}
示例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;
}