下面列出了怎么用io.grpc.Channel的API类实例代码及写法,或者点击链接到github查看源代码。
private static ClientInterceptor metadataInterceptor(Map<String, Object> metaDataMap) {
return new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, final Channel next) {
return new CheckedForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
protected void checkedStart(Listener<RespT> responseListener, Metadata headers) {
metaDataMap.forEach((k, v) -> {
Key<String> mKey = Key.of(k, ASCII_STRING_MARSHALLER);
headers.put(mKey, String.valueOf(v));
});
delegate().start(responseListener, headers);
}
};
}
};
}
private GRPCChannel(String host, int port, List<ChannelBuilder> channelBuilders,
List<ChannelDecorator> decorators) throws Exception {
ManagedChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port);
for (ChannelBuilder builder : channelBuilders) {
channelBuilder = builder.build(channelBuilder);
}
this.originChannel = channelBuilder.build();
Channel channel = originChannel;
for (ChannelDecorator decorator : decorators) {
channel = decorator.build(channel);
}
channelWithDecorators = channel;
}
@Test
public void missingBlobReadIsNotFound() {
ByteString helloWorld = ByteString.copyFromUtf8("Hello, World!");
Digest digest = DIGEST_UTIL.compute(helloWorld);
Channel channel = InProcessChannelBuilder.forName(fakeServerName).directExecutor().build();
ByteStreamBlockingStub service = ByteStreamGrpc.newBlockingStub(channel);
when(simpleBlobStore.get(eq(digest.getHash()), any(OutputStream.class)))
.thenReturn(immediateFuture(false));
ReadRequest request =
ReadRequest.newBuilder().setResourceName(createBlobDownloadResourceName(digest)).build();
StatusRuntimeException notFoundException = null;
try {
if (service.read(request).hasNext()) {
fail("no responses should be available");
}
} catch (StatusRuntimeException e) {
assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Code.NOT_FOUND);
notFoundException = e;
}
assertThat(notFoundException).isNotNull();
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
// New RPCs on client-side inherit the tag context from the current Context.
TagContext parentCtx = tagger.getCurrentTagContext();
final ClientCallTracer tracerFactory =
newClientCallTracer(parentCtx, method.getFullMethodName());
ClientCall<ReqT, RespT> call =
next.newCall(method, callOptions.withStreamTracerFactory(tracerFactory));
return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
delegate().start(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onClose(Status status, Metadata trailers) {
tracerFactory.callEnded(status);
super.onClose(status, trailers);
}
},
headers);
}
};
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT,RespT> method, CallOptions callOptions, Channel next) {
LOGGER.info("Intercepted " + method.getFullMethodName());
ClientCall<ReqT, RespT> call = next.newCall(method, callOptions);
call = new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
if (apiKey != null && !apiKey.isEmpty()) {
LOGGER.info("Attaching API Key: " + apiKey);
headers.put(API_KEY_HEADER, apiKey);
}
if (authToken != null && !authToken.isEmpty()) {
System.out.println("Attaching auth token");
headers.put(AUTHORIZATION_HEADER, "Bearer " + authToken);
}
super.start(responseListener, headers);
}
};
return call;
}
@Test public void userInterceptor_throwsOnHalfClose() {
closeClient(client);
client = newClient(new ClientInterceptor() {
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions,
Channel channel) {
ClientCall<ReqT, RespT> call = channel.newCall(methodDescriptor, callOptions);
return new SimpleForwardingClientCall<ReqT, RespT>(call) {
@Override public void halfClose() {
throw new IllegalStateException("I'm a bad interceptor.");
}
};
}
}, grpcTracing.newClientInterceptor());
assertThatThrownBy(() -> GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST))
.isInstanceOf(IllegalStateException.class);
testSpanHandler.takeRemoteSpanWithErrorMessage(CLIENT, "I'm a bad interceptor.");
}
/**
* Creates a protocol negotiator for ALTS on the server side.
*/
public static ProtocolNegotiator serverAltsProtocolNegotiator(
ObjectPool<Channel> handshakerChannelPool) {
final LazyChannel lazyHandshakerChannel = new LazyChannel(handshakerChannelPool);
final class ServerTsiHandshakerFactory implements TsiHandshakerFactory {
@Override
public TsiHandshaker newHandshaker(@Nullable String authority) {
assert authority == null;
return AltsTsiHandshaker.newServer(
HandshakerServiceGrpc.newStub(lazyHandshakerChannel.get()),
new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions()));
}
}
return new ServerAltsProtocolNegotiator(
new ServerTsiHandshakerFactory(), lazyHandshakerChannel);
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
final MethodDescriptor<ReqT, RespT> method, CallOptions callOptions,
final Channel next) {
return new ClientInterceptors.CheckedForwardingClientCall<ReqT, RespT>(
next.newCall(method, callOptions)) {
@Override
protected void checkedStart(Listener<RespT> responseListener, Metadata headers)
throws StatusException {
Metadata cachedSaved;
URI uri = serviceUri(next, method);
synchronized (this) {
Map<String, List<String>> latestMetadata = getRequestMetadata(uri);
if (mLastMetadata == null || mLastMetadata != latestMetadata) {
mLastMetadata = latestMetadata;
mCached = toHeaders(mLastMetadata);
}
cachedSaved = mCached;
}
headers.merge(cachedSaved);
delegate().start(responseListener, headers);
}
};
}
@Test
public void testClientRandomStubTest() throws IllegalAccessException {
int NUM_ITER = 1000;
HashMap<String, Integer> counts = new HashMap<>();
for (int i = 0; i < NUM_ITER; i++) {
Transaction txn = dgraphClient.newTransaction();
Channel channel = (Channel) channelField.get(stubField.get(asyncTransactionField.get(txn)));
String endpoint = channel.authority();
counts.put(endpoint, counts.getOrDefault(endpoint, 0) + 1);
}
// Ensure that we got all the clients
assertEquals(counts.size(), 3);
int sum = 0;
for (Map.Entry<String, Integer> ep : counts.entrySet()) {
assertTrue(ep.getValue() > 300);
sum += ep.getValue();
}
assertEquals(sum, NUM_ITER);
}
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
GrpcWorker worker = new GrpcWorker();
//"test.proto"
// String protilFileName = "test.proto";
// ProtoFile protoFile = worker.parserProtoFile(protilFileName);
// // "/v1/example/hello"
// worker.listProtoServiceInProtoFile(protoFile);
// GrpcServiceDefine grpcService = worker.findGrpcService("/v1/example/hello", "post");
// System.out.println("grpcService:" + grpcService);
DynamicMultiClassLoader loader = DynamicMultiClassLoader.getLoader(URLTools.toUrl(Consts.JAVA_OUT_DIR));
Class grpc = loader.loadClass("df.open.grpc.hello.HelloServiceGrpc");
Class proto = loader.loadClass("df.open.grpc.hello.HelloServiceProto");
Method newBlockingStub = grpc.getMethod("newBlockingStub", Channel.class);
System.out.println(newBlockingStub);
AbstractStub stub = (AbstractStub) newBlockingStub.invoke(grpc, channel);
System.out.println(stub);
}
public static FileDescriptorSet resolveService(Channel channel, String serviceName) {
ServerReflectionClient reflectionClient = ServerReflectionClient.create(channel);
try {
List<String> serviceNames = reflectionClient.listServices().get();
if (!serviceNames.contains(serviceName)) {
throw Status.NOT_FOUND.withDescription(
String.format("Remote server does not have service %s. Services: %s", serviceName, serviceNames))
.asRuntimeException();
}
return reflectionClient.lookupService(serviceName).get();
} catch (InterruptedException | ExecutionException e) {
logger.error("Resolve services get error", e);
throw new RuntimeException(e);
}
}
public GrpcClient(final Endpoint address, final SharedResources sharedResources, final ISettings settings) {
this.address = address;
this.settings = settings;
this.grpcExecutor = sharedResources.getClientChannelExecutor();
this.backgroundExecutor = sharedResources.getBackgroundExecutor();
this.eventLoopGroup = settings.getUseInProcessTransport() ? null : sharedResources.getEventLoopGroup();
final RemovalListener<Endpoint, Channel> removalListener =
removal -> shutdownChannel((ManagedChannel) removal.getValue());
this.channelMap = CacheBuilder.newBuilder()
.expireAfterAccess(30, TimeUnit.SECONDS)
.removalListener(removalListener)
.build(new CacheLoader<Endpoint, Channel>() {
@Override
public Channel load(final Endpoint endpoint) {
return getChannel(endpoint);
}
});
}
private void warmup(SimpleRequest req, List<? extends Channel> channels) throws Exception {
long endTime = System.nanoTime() + TimeUnit.SECONDS.toNanos(config.warmupDuration);
doBenchmark(req, channels, endTime);
// I don't know if this helps, but it doesn't hurt trying. We sometimes run warmups
// of several minutes at full load and it would be nice to start the actual benchmark
// with a clean heap.
System.gc();
}
SimulatedRemoteMesosSchedulerDriver(Protos.MasterInfo masterInfo, Channel channel, Scheduler callbackHandler, TitusRuntime titusRuntime) {
this.masterInfo = masterInfo;
this.asyncClient = SimulatedMesosServiceGrpc.newStub(channel);
this.blockingClient = SimulatedMesosServiceGrpc.newBlockingStub(channel);
this.callbackHandler = callbackHandler;
this.titusRuntime = titusRuntime;
}
@Bean(name = TITUS_MASTER_CHANNEL)
public Channel getManagedChannel(TitusMasterClientConfiguration configuration, LeaderResolver leaderResolver, TitusRuntime titusRuntime) {
return NettyChannelBuilder
.forTarget("leader://titusmaster")
.nameResolverFactory(new LeaderNameResolverFactory(leaderResolver, configuration.getMasterGrpcPort(), titusRuntime))
.usePlaintext(true)
.maxHeaderListSize(65536)
.build();
}
/**
* NOTE: for this to work, the tracing interceptor must be last (so that it executes first)
*
* <p>Also notice that we are only making the current context available in the request side.
*/
@Test public void currentSpanVisibleToUserInterceptors() {
closeClient(client);
client = newClient(
new ClientInterceptor() {
@Override public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
tracing.tracer().currentSpanCustomizer().annotate("start");
super.start(responseListener, headers);
}
@Override public void sendMessage(ReqT message) {
tracing.tracer().currentSpanCustomizer().annotate("sendMessage");
super.sendMessage(message);
}
};
}
},
grpcTracing.newClientInterceptor()
);
GreeterGrpc.newBlockingStub(client).sayHello(HELLO_REQUEST);
assertThat(testSpanHandler.takeRemoteSpan(CLIENT).annotations())
.extracting(Entry::getValue)
.containsOnly("start", "sendMessage");
}
/**
* A custom client.
*/
private CustomHeaderClient(String host, int port) {
originChannel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
ClientInterceptor interceptor = new HeaderClientInterceptor();
Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
if (MethodDescriptor.MethodType.CLIENT_STREAMING == method.getType()) {
if (logger.isDebugEnabled()) {
logger.debug("interceptCall {}", method.getFullMethodName());
}
final ClientCall<ReqT, RespT> newCall = next.newCall(method, callOptions);
return new DiscardClientCall<ReqT, RespT>(newCall, this.listener, maxPendingThreshold);
} else {
return next.newCall(method, callOptions);
}
}
@Test
public void serverHeaderDeliveredToClient() {
class SpyingClientInterceptor implements ClientInterceptor {
ClientCall.Listener<?> spyListener;
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
spyListener = responseListener =
mock(ClientCall.Listener.class, delegatesTo(responseListener));
super.start(responseListener, headers);
}
};
}
}
SpyingClientInterceptor clientInterceptor = new SpyingClientInterceptor();
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(channel)
.withInterceptors(clientInterceptor);
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
blockingStub.sayHello(HelloRequest.getDefaultInstance());
assertNotNull(clientInterceptor.spyListener);
verify(clientInterceptor.spyListener).onHeaders(metadataCaptor.capture());
assertEquals(
"customRespondValue",
metadataCaptor.getValue().get(HeaderServerInterceptor.CUSTOM_HEADER_KEY));
}
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new CheckedForwardingClientCall<ReqT, RespT>(
next.newCall(method.toBuilder().setSafe(true).build(), callOptions)) {
@Override
public void checkedStart(Listener<RespT> responseListener, Metadata headers) {
delegate().start(responseListener, headers);
}
};
}
@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)
);
}
@Bean
@Named(GATEWAY_CHANNEL)
public Channel getGatewayChannel(ApplicationArguments arguments) {
List<String> gateway = arguments.getOptionValues("gateway");
String gatewayAddress = CollectionsExt.isNullOrEmpty(gateway) ? "localhost:8091" : gateway.get(0);
return NettyChannelBuilder
.forTarget(gatewayAddress)
.usePlaintext(true)
.maxHeaderListSize(65536)
.build();
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (ReflectUtils.isToStringMethod(method)) {
return AbstractClientInvocation.this.toString();
} else {
GrpcRequest request = this.buildGrpcRequest(method, args);
MethodType methodType = request.getMethodType();
Channel channel = request.getChannel();
try {
switch (methodType) {
case UNARY:
return unaryCall(request, channel);
case CLIENT_STREAMING:
return streamCall(request, channel);
case SERVER_STREAMING:
return streamCall(request, channel);
case BIDI_STREAMING:
return streamCall(request, channel);
default:
RpcServiceException rpcFramwork =
new RpcServiceException(RpcErrorMsgConstant.SERVICE_UNFOUND);
throw rpcFramwork;
}
} finally {
Object remote = GrpcCallOptions.getAffinity(request.getRefUrl())
.get(GrpcCallOptions.GRPC_CURRENT_ADDR_KEY);
log.debug(String.format("Service: %s Method: %s RemoteAddress: %s",
request.getServiceName(), request.getMethodName(), String.valueOf(remote)));
}
}
}
public ThrottlingBlockingClient(Channel channel, String token) {
ThrottlingTestServiceGrpc.ThrottlingTestServiceBlockingStub stub =
ThrottlingTestServiceGrpc.newBlockingStub(channel);
//add metadata
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), token);
blockingStub = MetadataUtils.attachHeaders(stub,metadata);
}
LoadGenerationWorker(Channel channel, SimpleRequest request, int targetQps, int duration) {
stub = BenchmarkServiceGrpc.newStub(checkNotNull(channel, "channel"));
this.request = checkNotNull(request, "request");
this.targetQps = targetQps;
numRpcs = (long) targetQps * duration;
rnd = new Random();
}
/**
* If channel is null, gets a channel from the channel pool, otherwise, returns the cached
* channel.
*/
synchronized Channel get() {
if (channel == null) {
channel = channelPool.getObject();
}
return channel;
}
@Test
public void binaryLogInstalled() throws Exception {
final SettableFuture<Boolean> intercepted = SettableFuture.create();
channelBuilder.binlog = new BinaryLog() {
@Override
public void close() throws IOException {
// noop
}
@Override
public <ReqT, RespT> ServerMethodDefinition<?, ?> wrapMethodDefinition(
ServerMethodDefinition<ReqT, RespT> oMethodDef) {
return oMethodDef;
}
@Override
public Channel wrapChannel(Channel channel) {
return ClientInterceptors.intercept(channel,
new ClientInterceptor() {
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method,
CallOptions callOptions,
Channel next) {
intercepted.set(true);
return next.newCall(method, callOptions);
}
});
}
};
createChannel();
ClientCall<String, Integer> call = channel.newCall(method, CallOptions.DEFAULT);
call.start(mockCallListener, new Metadata());
assertTrue(intercepted.get());
}
@FXML
public void initialize() throws Exception {
Server server = ServerBuilder.forPort(9000).addService(this).build().start();
Channel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
stub = RxBackpressureDemoGrpc.newRxStub(channel);
producedSeries.setName("Produced");
consumedSeries.setName("Consumed");
lineChart.getData().add(producedSeries);
lineChart.getData().add(consumedSeries);
}
public EmeraldTransport(Channel channel,
ObjectMapper objectMapper,
RpcConverter rpcConverter,
ExecutorService executorService,
Common.ChainRef chainRef) {
this.channel = channel;
this.objectMapper = objectMapper;
this.rpcConverter = rpcConverter;
this.executorService = executorService;
this.chainRef = chainRef;
blockingStub = BlockchainGrpc.newBlockingStub(channel);
}
@Override
public Channel asChannel() {
return new SubchannelChannel(
subchannel, balancerRpcExecutorHolder.getExecutor(),
transportFactory.getScheduledExecutorService(),
callTracerFactory.create());
}