下面列出了怎么用io.grpc.ManagedChannel的API类实例代码及写法,或者点击链接到github查看源代码。
private void run(String[] args) throws InterruptedException {
parseArgs(args);
ExecutorService executor = Executors.newFixedThreadPool(1);
ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build();
try {
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build());
logger.log(Level.INFO, "Got {0}", resp);
} finally {
channel.shutdown();
channel.awaitTermination(1, TimeUnit.SECONDS);
// Wait until the channel has terminated, since tasks can be queued after the channel is
// shutdown.
executor.shutdown();
}
}
public StubInstance(
String name,
String identifier,
DigestUtil digestUtil,
ManagedChannel channel,
long deadlineAfter,
TimeUnit deadlineAfterUnits,
Retrier retrier,
@Nullable ListeningScheduledExecutorService retryService) {
this.name = name;
this.identifier = identifier;
this.digestUtil = digestUtil;
this.channel = channel;
this.deadlineAfter = deadlineAfter;
this.deadlineAfterUnits = deadlineAfterUnits;
this.retrier = retrier;
this.retryService = retryService;
}
@Test
public void updateOobChannelAddresses_newAddressConnects() {
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, new Metadata()); // Create LB
ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
verify(mockLoadBalancerFactory).newLoadBalancer(helperCaptor.capture());
Helper helper = helperCaptor.getValue();
ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost");
oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
MockClientTransportInfo t0 = newTransports.poll();
t0.listener.transportReady();
helper.updateOobChannelAddresses(oobChannel, servers.get(1));
oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
MockClientTransportInfo t1 = newTransports.poll();
t1.listener.transportReady();
}
public static void main(String[] args) throws Exception {
// STEP1 构造 Channel 和 BlockingStub
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", Constant.RUNNING_PORT)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid needing certificates.
.usePlaintext()
.build();
UserRpcServiceGrpc.UserRpcServiceBlockingStub blockingStub = UserRpcServiceGrpc.newBlockingStub(channel);
int requestAge = 20;
logger.info("Will try to query age = " + requestAge + " ...");
// STEP2 发起 gRPC 请求
UserRpcProto.AgeRequest request = UserRpcProto.AgeRequest.newBuilder().setAge(20).build();
try {
UserRpcProto.UserResponse response = blockingStub.listByAge(request);
logger.info("Response: " + ProtoUtils.toStr(response));
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
} finally {
// STEP3 关闭 Channel
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
}
public UcoreInterface.SubscribeNodesOutput subscribeNodes(UcoreInterface.SubscribeNodesInput subscribeNodesInput) throws IOException {
try {
return stub.withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS).subscribeNodes(subscribeNodesInput);
} catch (Exception e) {
//the first try failure ,try for all the other ucore ip
for (String ip : getIpList()) {
ManagedChannel channel = null;
try {
channel = ManagedChannelBuilder.forAddress(ip,
Integer.parseInt(getValue(ClusterParamCfg.CLUSTER_PLUGINS_PORT))).usePlaintext(true).build();
stub = UcoreGrpc.newBlockingStub(channel).withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS);
return stub.withDeadlineAfter(GRPC_SUBTIMEOUT, TimeUnit.SECONDS).subscribeNodes(subscribeNodesInput);
} catch (Exception e2) {
LOGGER.info("try connection IP " + ip + " failure ", e2);
if (channel != null) {
channel.shutdownNow();
}
}
}
}
throw new IOException("ALL the ucore connect failure");
}
public static TransportChannelProvider getChannelProvider() {
ManagedChannel channel = null;
if (USE_SSL) {
try {
channel =
NettyChannelBuilder.forAddress(LOCALHOST, PORT)
.maxInboundMessageSize(100000)
.sslContext(
GrpcSslContexts.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build())
.overrideAuthority(LOCALHOST + ":" + PORT)
.build();
} catch (SSLException e) {
fail("Unable to create SSL channel " + e.getMessage());
}
} else {
channel = ManagedChannelBuilder.forAddress(LOCALHOST, PORT).usePlaintext(true).build();
}
return FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
}
private void handleDataMessage(Map<String, String> dataMap) {
try {
Utils.initialize(this);
// Get the encryption algorithm and the ciphertext bytes.
KeyAlgorithm keyAlgorithm =
KeyAlgorithm.valueOf(dataMap.get(Constants.CAPILLARY_KEY_ALGORITHM_KEY));
byte[] ciphertext = Base64.decode(dataMap.get(Constants.CAPILLARY_CIPHERTEXT_KEY));
// Create the gRPC channel.
ManagedChannel channel = Utils.createGrpcChannel(this);
// Create the DemoCapillaryHandler.
DemoCapillaryHandler handler = new DemoCapillaryHandler(this, channel);
// Handle ciphertext.
Utils.getKeyManager(this, keyAlgorithm)
.getDecrypterManager().decrypt(ciphertext, handler, keyAlgorithm);
// Close the gRPC channel.
channel.shutdown();
} catch (GeneralSecurityException | IOException e) {
e.printStackTrace();
}
}
@Test
public void updateOobChannelAddresses_existingAddressDoesNotConnect() {
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, new Metadata()); // Create LB
ArgumentCaptor<Helper> helperCaptor = ArgumentCaptor.forClass(null);
verify(mockLoadBalancerProvider).newLoadBalancer(helperCaptor.capture());
Helper helper = helperCaptor.getValue();
ManagedChannel oobChannel = helper.createOobChannel(servers.get(0), "localhost");
oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
MockClientTransportInfo t0 = newTransports.poll();
t0.listener.transportReady();
List<SocketAddress> changedList = new ArrayList<>(servers.get(0).getAddresses());
changedList.add(new FakeSocketAddress("aDifferentServer"));
helper.updateOobChannelAddresses(oobChannel, new EquivalentAddressGroup(changedList));
oobChannel.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
assertNull(newTransports.poll());
}
@Override
protected ManagedChannel createChannel() {
try {
NettyChannelBuilder builder = NettyChannelBuilder
.forAddress(TestUtils.testServerAddress(getPort()))
.flowControlWindow(65 * 1024)
.maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
.sslContext(GrpcSslContexts
.forClient()
.keyManager(TestUtils.loadCert("client.pem"), TestUtils.loadCert("client.key"))
.trustManager(TestUtils.loadX509Cert("ca.pem"))
.ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE)
.build());
io.grpc.internal.TestingAccessor.setStatsImplementation(
builder, createClientCensusStatsModule());
return builder.build();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@After
public void teardown() throws Exception {
// All scheduled tasks have been accounted for
assertThat(clock.getPendingTasks()).isEmpty();
// Health-check streams are usually not closed in the tests because handleSubchannelState() is
// faked. Force closing for clean up.
for (Server server : servers) {
server.shutdownNow();
assertThat(server.awaitTermination(1, TimeUnit.SECONDS)).isTrue();
}
for (ManagedChannel channel : channels) {
channel.shutdownNow();
assertThat(channel.awaitTermination(1, TimeUnit.SECONDS)).isTrue();
}
for (HealthImpl impl : healthImpls) {
assertThat(impl.checkCalled).isFalse();
}
}
@Before
public void setUp() throws Exception {
// Generate a unique in-process server name.
String serverName = InProcessServerBuilder.generateName();
// Create a server, add service, start, and register for automatic graceful shutdown.
grpcCleanup.register(InProcessServerBuilder
.forName(serverName).directExecutor().addService(serviceImpl).build().start());
// Create a client channel and register for automatic graceful shutdown.
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
// Create a HelloWorldClient using the in-process channel;
client = new HelloWorldClient(channel);
}
@Override
public void destroy(URI channelUri) {
checkNotNull(channelUri);
channelLocks.get(channelUri).lock();
try {
final ManagedChannel channel = channels.remove(channelUri);
if (channel != null) {
shutdownNowAndWait(channel, channelUri);
}
final GrpcLoggingInterceptor interceptor = interceptors.remove(channelUri);
if (interceptor != null) {
interceptor.close();
}
} finally {
channelLocks.get(channelUri).unlock();
}
}
public String testMethodLevelThrottling (String targetUrl, String requestText, String token) throws
InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forTarget(targetUrl).usePlaintext().build();
try {
ThrottlingBlockingClient client = new ThrottlingBlockingClient(channel, token);
for (int i=0; i<6; i++) {
client.testCallMethodThrottling(requestText);
}
return client.testCallMethodThrottling(requestText);
} finally {
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
}
TracedClient(
ManagedChannel channel,
long deadline,
String compression,
ClientInterceptor... interceptors) {
blockingStub =
GreeterGrpc.newBlockingStub(ClientInterceptors.intercept(channel, interceptors))
.withDeadlineAfter(deadline, TimeUnit.MILLISECONDS)
.withCompression(compression);
}
public static ManagedChannel getServerChannel()
{
final NettyChannelBuilder channelBuilder =
NettyChannelBuilder.forAddress(getServerHost(), getServerPort());
if (getBoolean(TLS))
{
final Path certificatesDir = Configuration.certificatesDirectory();
final SslContextBuilder sslClientContextBuilder = GrpcSslContexts.forClient()
.trustManager(certificatesDir.resolve("ca.pem").toFile())
.keyManager(
certificatesDir.resolve("client.pem").toFile(), certificatesDir.resolve("client.key").toFile());
try
{
channelBuilder.sslContext(sslClientContextBuilder.build());
}
catch (final SSLException ex)
{
LangUtil.rethrowUnchecked(ex);
}
}
else
{
channelBuilder.usePlaintext();
}
return channelBuilder.build();
}
@Test
public void oobChannelsWhenChannelShutdownNow() {
createChannel();
ManagedChannel oob1 = helper.createOobChannel(addressGroup, "oob1Authority");
ManagedChannel oob2 = helper.createOobChannel(addressGroup, "oob2Authority");
oob1.newCall(method, CallOptions.DEFAULT).start(mockCallListener, new Metadata());
oob2.newCall(method, CallOptions.DEFAULT).start(mockCallListener2, new Metadata());
assertThat(transports).hasSize(2);
MockClientTransportInfo ti1 = transports.poll();
MockClientTransportInfo ti2 = transports.poll();
ti1.listener.transportReady();
ti2.listener.transportReady();
channel.shutdownNow();
verify(ti1.transport).shutdownNow(any(Status.class));
verify(ti2.transport).shutdownNow(any(Status.class));
ti1.listener.transportShutdown(Status.UNAVAILABLE.withDescription("shutdown now"));
ti2.listener.transportShutdown(Status.UNAVAILABLE.withDescription("shutdown now"));
ti1.listener.transportTerminated();
assertFalse(channel.isTerminated());
ti2.listener.transportTerminated();
assertTrue(channel.isTerminated());
}
void closeClient(ManagedChannel client) {
client.shutdown();
try {
client.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new AssertionError(e);
}
}
@Override
public ManagedChannelBuilder<?> createResolvingOobChannelBuilder(String target) {
try {
grpcCleanupRule.register(
InProcessServerBuilder.forName(target)
.addService(fakeRlsServerImpl)
.directExecutor()
.build()
.start());
} catch (IOException e) {
throw new RuntimeException("cannot create server: " + target, e);
}
final InProcessChannelBuilder builder =
InProcessChannelBuilder.forName(target).directExecutor();
class CleaningChannelBuilder extends ForwardingChannelBuilder<CleaningChannelBuilder> {
@Override
protected ManagedChannelBuilder<?> delegate() {
return builder;
}
@Override
public ManagedChannel build() {
return grpcCleanupRule.register(super.build());
}
}
return new CleaningChannelBuilder();
}
@Override
protected void configure() {
ManagedChannel channel = ManagedChannelBuilder.forAddress(HOST, PORT).usePlaintext().build();
bind(ShelfServiceGrpc.ShelfServiceFutureStub.class)
.toInstance(ShelfServiceGrpc.newFutureStub(channel));
bind(ShelfServiceGrpc.ShelfServiceBlockingStub.class)
.toInstance(ShelfServiceGrpc.newBlockingStub(channel));
}
@VisibleForTesting
void runStressTest() throws Exception {
Preconditions.checkState(!shutdown, "client was shutdown.");
if (testCaseWeightPairs.isEmpty()) {
return;
}
int numChannels = addresses.size() * channelsPerServer;
int numThreads = numChannels * stubsPerChannel;
threadpool = MoreExecutors.listeningDecorator(newFixedThreadPool(numThreads));
int serverIdx = -1;
for (InetSocketAddress address : addresses) {
serverIdx++;
for (int i = 0; i < channelsPerServer; i++) {
ManagedChannel channel = createChannel(address);
channels.add(channel);
for (int j = 0; j < stubsPerChannel; j++) {
String gaugeName =
String.format("/stress_test/server_%d/channel_%d/stub_%d/qps", serverIdx, i, j);
Worker worker =
new Worker(channel, testCaseWeightPairs, durationSecs, gaugeName);
workerFutures.add(threadpool.submit(worker));
}
}
}
}
Worker(ManagedChannel channel, List<TestCaseWeightPair> testCaseWeightPairs,
int durationSec, String gaugeName) {
Preconditions.checkArgument(durationSec >= -1, "durationSec must be gte -1.");
this.channel = Preconditions.checkNotNull(channel, "channel");
this.testCaseWeightPairs =
Preconditions.checkNotNull(testCaseWeightPairs, "testCaseWeightPairs");
this.durationSec = durationSec == -1 ? null : durationSec;
this.gaugeName = Preconditions.checkNotNull(gaugeName, "gaugeName");
}
@Test
public void hostnameVerifierWithCorrectHostname() throws Exception {
ManagedChannel channel = createChannelBuilder()
.overrideAuthority(GrpcUtil.authorityFromHostAndPort(
TestUtils.TEST_SERVER_HOST, getPort()))
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return false;
}
})
.build();
TestServiceGrpc.TestServiceBlockingStub blockingStub =
TestServiceGrpc.newBlockingStub(channel);
Throwable actualThrown = null;
try {
blockingStub.emptyCall(Empty.getDefaultInstance());
} catch (Throwable t) {
actualThrown = t;
}
assertNotNull("The rpc should have been failed due to hostname verification", actualThrown);
Throwable cause = Throwables.getRootCause(actualThrown);
assertTrue(
"Failed by unexpected exception: " + cause, cause instanceof SSLPeerUnverifiedException);
channel.shutdown();
}
public CloudSpeechSession(
CloudSpeechSessionParams params,
SpeechSessionListener speechSessionListener,
int sampleRateHz,
ManagedChannel channel) {
this.params = params;
this.channel = channel;
this.speechSessionListener = speechSessionListener;
this.sampleRateHz = sampleRateHz;
this.encoder = new StreamingAudioEncoder();
}
/**
* Create new connection
*
* @param url
*/
private ManagedChannel initChannel(ProviderInfo url) {
ClientInterceptor clientHeaderClientInterceptor = buildClientHeaderClientInterceptor();
NettyChannelBuilder builder = NettyChannelBuilder.forAddress(url.getHost(), url.getPort());
builder.usePlaintext();
builder.disableRetry();
builder.intercept(clientHeaderClientInterceptor);
return builder.build();
}
@Test
void longMaxRequestLimit() throws Exception {
final ManagedChannel channel =
ManagedChannelBuilder.forAddress("127.0.0.1", serverWithLongMaxRequestLimit.httpPort())
.usePlaintext()
.build();
try {
final UnitTestServiceBlockingStub stub = UnitTestServiceGrpc.newBlockingStub(channel);
assertThat(stub.staticUnaryCall(REQUEST_MESSAGE)).isEqualTo(RESPONSE_MESSAGE);
} finally {
channel.shutdownNow();
requestLogQueue.take();
}
}
private static void setupJaegerExporter() {
ManagedChannel jaegerChannel =
ManagedChannelBuilder.forAddress("127.0.0.1", jaegerContainer.getMappedPort(COLLECTOR_PORT))
.usePlaintext()
.build();
SpanExporter jaegerExporter =
JaegerGrpcSpanExporter.newBuilder()
.setServiceName(SERVICE_NAME)
.setChannel(jaegerChannel)
.setDeadlineMs(30000)
.build();
OpenTelemetrySdk.getTracerProvider()
.addSpanProcessor(SimpleSpanProcessor.newBuilder(jaegerExporter).build());
}
String getStatus() {
ManagedChannel lmanagedChannel = managedChannel;
if (lmanagedChannel == null) {
return "No grpc managed channel active. peer eventing client service is shutdown: " + shutdown;
} else {
StringBuilder sb = new StringBuilder(1000);
sb.append("peer eventing client service is shutdown: ").append(shutdown)
.append(", grpc isShutdown: ").append(lmanagedChannel.isShutdown())
.append(", grpc isTerminated: ").append(lmanagedChannel.isTerminated())
.append(", grpc state: ").append("" + lmanagedChannel.getState(false));
return sb.toString();
}
}
@Override
public <T> T get(
BeanResolutionContext resolutionContext,
BeanDefinition<T> beanDefinition,
BeanIdentifier identifier,
Provider<T> provider) {
BeanResolutionContext.Segment segment = resolutionContext.getPath().currentSegment().orElseThrow(() ->
new IllegalStateException("@GrpcChannel used in invalid location")
);
Argument argument = segment.getArgument();
String value = argument.getAnnotationMetadata().getValue(GrpcChannel.class, String.class).orElse(null);
if (StringUtils.isEmpty(value)) {
throw new DependencyInjectionException(resolutionContext, argument, "No value specified to @GrpcChannel annotation");
}
if (!Channel.class.isAssignableFrom(argument.getType())) {
throw new DependencyInjectionException(resolutionContext, argument, "@GrpcChannel used on type that is not a Channel");
}
if ("grpc-server".equalsIgnoreCase(value)) {
return (T) applicationContext.getBean(ManagedChannel.class, Qualifiers.byName("grpc-server"));
}
if (!(provider instanceof ParametrizedProvider)) {
throw new DependencyInjectionException(resolutionContext, argument, "GrpcChannelScope called with invalid bean provider");
}
value = applicationContext.resolveRequiredPlaceholders(value);
String finalValue = value;
return (T) channels.computeIfAbsent(new ChannelKey(identifier, value), channelKey ->
(ManagedChannel) ((ParametrizedProvider<T>) provider).get(finalValue)
);
}
/**
* Check that channel is a singleton.
*/
@Test
public void channelBean() {
final ManagedChannel channel1 = applicationContext.getBean(ManagedChannel.class);
final ManagedChannel channel2 = applicationContext.getBean(ManagedChannel.class);
Assert.assertNotNull(channel1);
Assert.assertNotNull(channel2);
Assert.assertSame(channel1, channel2);
}
@Override
public ManagedChannel shutdown() {
if (referenceCount.decrementAndGet() <= 0) {
return grpcChannel.shutdown();
}
return grpcChannel;
}