下面列出了io.grpc.ForwardingClientCall.SimpleForwardingClientCall#io.grpc.ClientInterceptors 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Channel createChannel(final String name, final List<ClientInterceptor> customInterceptors,
final boolean sortInterceptors) {
final Channel channel;
synchronized (this) {
if (this.shutdown) {
throw new IllegalStateException("GrpcChannelFactory is already closed!");
}
channel = this.channels.computeIfAbsent(name, this::newManagedChannel);
}
final List<ClientInterceptor> interceptors =
Lists.newArrayList(this.globalClientInterceptorRegistry.getClientInterceptors());
interceptors.addAll(customInterceptors);
if (sortInterceptors) {
this.globalClientInterceptorRegistry.sortInterceptors(interceptors);
}
return ClientInterceptors.interceptForward(channel, interceptors);
}
@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);
}
};
}
@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 (GoogleCredentialsInterceptor.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);
}
};
}
@Override
public Channel createChannel(final String name, final List<ClientInterceptor> customInterceptors,
final boolean sortInterceptors) {
final Channel channel;
synchronized (this) {
if (this.shutdown) {
throw new IllegalStateException("GrpcChannelFactory is already closed!");
}
channel = this.channels.computeIfAbsent(name, this::newManagedChannel);
}
final List<ClientInterceptor> interceptors =
Lists.newArrayList(this.globalClientInterceptorRegistry.getClientInterceptors());
interceptors.addAll(customInterceptors);
if (sortInterceptors) {
this.globalClientInterceptorRegistry.sortInterceptors(interceptors);
}
return ClientInterceptors.interceptForward(channel, interceptors);
}
@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);
}
};
}
/**
* Initializes a connection to the gRPC server.
* @return a boolean indicating the success.
*/
private boolean initServerConnection() {
if(!mConnected) {
mInterceptor = new AuthHeaderClientInterceptor(
getUserIdToken());
try {
mChannelImpl = OkHttpChannelBuilder
.forAddress(AndroidConstants.HOST,
AndroidConstants.PORT)
.build();
Channel mOriginChannel = ClientInterceptors
.intercept(mChannelImpl, mInterceptor);
mBlockingStub = AbelanaGrpc.newBlockingStub(mOriginChannel);
mConnected = true;
} catch (RuntimeException e) {
mConnected = false;
}
}
return mConnected;
}
@Before
public final void setUp() throws Exception {
// Use a mutable service registry for later registering the service impl for each test case.
fakeServer =
InProcessServerBuilder.forName(fakeServerName)
.fallbackHandlerRegistry(serviceRegistry)
.directExecutor()
.build()
.start();
logStream = Mockito.mock(AsynchronousFileOutputStream.class);
clock = new ManualClock();
interceptor = new LoggingInterceptor(logStream, clock);
loggedChannel =
ClientInterceptors.intercept(
InProcessChannelBuilder.forName(fakeServerName).directExecutor().build(), interceptor);
}
/**
* 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);
}
@Test
public void clientHeaderDeliveredToServer() 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(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor))
.build().start());
// Create a client channel and register for automatic graceful shutdown.
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
ClientInterceptors.intercept(channel, new HeaderClientInterceptor()));
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
try {
blockingStub.sayHello(HelloRequest.getDefaultInstance());
fail();
} catch (StatusRuntimeException expected) {
// expected because the method is not implemented at server side
}
verify(mockServerInterceptor).interceptCall(
Matchers.<ServerCall<HelloRequest, HelloReply>>any(),
metadataCaptor.capture(),
Matchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
assertEquals(
"customRequestValue",
metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
@Before
public void setUp() throws Exception {
grpcServerRule
.getServiceRegistry()
.addService(
ServerInterceptors.intercept(greeterServiceImpl, injectCacheControlInterceptor));
grpcServerRule.getServiceRegistry().addService(anotherGreeterServiceImpl);
baseChannel = grpcServerRule.getChannel();
SafeMethodCachingInterceptor interceptor =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptor);
}
@Test
public void invalidResponseMaxAge_usesDefault() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
cacheControlDirectives.add("max-age=-10");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertEquals(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
@Test
public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */
public void cacheableUnary() {
// Set safe to true.
MethodDescriptor<SimpleRequest, SimpleResponse> safeCacheableUnaryCallMethod =
TestServiceGrpc.getCacheableUnaryCallMethod().toBuilder().setSafe(true).build();
// Set fake user IP since some proxies (GFE) won't cache requests from localhost.
Metadata.Key<String> userIpKey = Metadata.Key.of("x-user-ip", Metadata.ASCII_STRING_MARSHALLER);
Metadata metadata = new Metadata();
metadata.put(userIpKey, "1.2.3.4");
Channel channelWithUserIpKey =
ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata));
SimpleRequest requests1And2 =
SimpleRequest.newBuilder()
.setPayload(
Payload.newBuilder()
.setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
.build();
SimpleRequest request3 =
SimpleRequest.newBuilder()
.setPayload(
Payload.newBuilder()
.setBody(ByteString.copyFromUtf8(String.valueOf(System.nanoTime()))))
.build();
SimpleResponse response1 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
SimpleResponse response2 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, requests1And2);
SimpleResponse response3 =
ClientCalls.blockingUnaryCall(
channelWithUserIpKey, safeCacheableUnaryCallMethod, CallOptions.DEFAULT, request3);
assertEquals(response1, response2);
assertNotEquals(response1, response3);
}
/**
* A custom client.
*/
private CustomHeaderClient(String host, int port) {
String target = "zookeeper:///" + GreeterGrpc.SERVICE_NAME;
originChannel = ManagedChannelBuilder
//.forAddress(host, port)
.forTarget(target)
.usePlaintext()
.build();
ClientInterceptor interceptor = new HeaderClientInterceptor();
Channel channel = ClientInterceptors.intercept(originChannel, interceptor);
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
@Provides
@FirebaseAppScope
public InAppMessagingSdkServingBlockingStub providesInAppMessagingSdkServingStub(
Channel channel, Metadata metadata) {
return InAppMessagingSdkServingGrpc.newBlockingStub(
ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata)));
}
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
inAppMessagingSdkServingBlockingStub =
InAppMessagingSdkServingGrpc.newBlockingStub(
ClientInterceptors.intercept(
grpcServerRule.getChannel(),
MetadataUtils.newAttachHeadersInterceptor(testMetadata)));
grpcClient = new GrpcClient(inAppMessagingSdkServingBlockingStub);
}
TracedClient(
ManagedChannel channel,
long deadline,
String compression,
ClientInterceptor... interceptors) {
blockingStub =
GreeterGrpc.newBlockingStub(ClientInterceptors.intercept(channel, interceptors))
.withDeadlineAfter(deadline, TimeUnit.MILLISECONDS)
.withCompression(compression);
}
public Driver(Builder builder) {
this.segments = builder.segments;
this.runtime = builder.runtimeSeconds;
this.latencyAccumulator = builder.latencyAccumulator;
Metadata metadata = new Metadata();
metadata.put(ID_HEADER, builder.id);
this.channel = ClientInterceptors.intercept(NettyChannelBuilder.forTarget("localhost:" + builder.port)
.usePlaintext(true)
.build(),
MetadataUtils.newAttachHeadersInterceptor(metadata));
}
/** Return {@link io.grpc.Channel} which is used by Cloud Pub/Sub gRPC API's. */
public static Channel getChannel(CredentialsProvider credentialsProvider) throws IOException {
ManagedChannel channelImpl =
NettyChannelBuilder.forAddress(ENDPOINT, 443)
.negotiationType(NegotiationType.TLS)
// Maximum Pub/Sub message size is 10MB.
.maxInboundMessageSize(10 * 1024 * 1024)
.build();
final ClientAuthInterceptor interceptor =
new ClientAuthInterceptor(
credentialsProvider.getCredentials(),
Executors.newCachedThreadPool());
return ClientInterceptors.intercept(channelImpl, interceptor);
}
/** Return channel with interceptor for returning credentials. */
private Channel newChannel() throws IOException {
checkState(publisherChannel != null, "PubsubGrpcClient has been closed");
ClientAuthInterceptor interceptor =
new ClientAuthInterceptor(credentials, Executors.newSingleThreadExecutor());
return ClientInterceptors.intercept(publisherChannel, interceptor);
}
/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HelloWorldClient(String address, String apiKey) {
channel = ManagedChannelBuilder.forTarget(address)
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
// needing certificates.
.usePlaintext(true)
.build();
Channel ch = ClientInterceptors.intercept(channel, new Interceptor(apiKey));
blockingStub = GreeterGrpc.newBlockingStub(ch);
}
static BookstoreGrpc.BookstoreBlockingStub createBookstoreStub(
String address, String apiKey, String authToken) {
Channel channel = ManagedChannelBuilder.forTarget(address)
.usePlaintext(true)
.build();
channel = ClientInterceptors.intercept(channel, new Interceptor(apiKey, authToken));
return BookstoreGrpc.newBlockingStub(channel);
}
@PostConstruct
public void up() {
channel = ManagedChannelBuilder.forAddress(gprcProviderHost, grpcProviderPort).usePlaintext(true).build();
greeterStub = GreeterGrpc.newStub(ClientInterceptors.intercept(channel, new ConsumerInterceptor()));
greeterBlockingStub = GreeterBlockingGrpc.newBlockingStub(ClientInterceptors.intercept(channel, new ConsumerInterceptor()));
greeterBlockingErrorStub = GreeterBlockingErrorGrpc.newBlockingStub(ClientInterceptors.intercept(channel, new ConsumerInterceptor()));
}
public static void main(final String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Please specify your project name.");
System.exit(1);
}
final String project = args[0];
ManagedChannelImpl channelImpl = NettyChannelBuilder
.forAddress("pubsub.googleapis.com", 443)
.negotiationType(NegotiationType.TLS)
.build();
GoogleCredentials creds = GoogleCredentials.getApplicationDefault();
// Down-scope the credential to just the scopes required by the service
creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub"));
// Intercept the channel to bind the credential
ExecutorService executor = Executors.newSingleThreadExecutor();
ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor);
Channel channel = ClientInterceptors.intercept(channelImpl, interceptor);
// Create a stub using the channel that has the bound credential
PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel);
ListTopicsRequest request = ListTopicsRequest.newBuilder()
.setPageSize(10)
.setProject("projects/" + project)
.build();
ListTopicsResponse resp = publisherStub.listTopics(request);
System.out.println("Found " + resp.getTopicsCount() + " topics.");
for (Topic topic : resp.getTopicsList()) {
System.out.println(topic.getName());
}
}
/**
* 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);
}
@Test
public void clientHeaderDeliveredToServer() 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(ServerInterceptors.intercept(new GreeterImplBase() {}, mockServerInterceptor))
.build().start());
// Create a client channel and register for automatic graceful shutdown.
ManagedChannel channel = grpcCleanup.register(
InProcessChannelBuilder.forName(serverName).directExecutor().build());
GreeterBlockingStub blockingStub = GreeterGrpc.newBlockingStub(
ClientInterceptors.intercept(channel, new HeaderClientInterceptor()));
ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
try {
blockingStub.sayHello(HelloRequest.getDefaultInstance());
fail();
} catch (StatusRuntimeException expected) {
// expected because the method is not implemented at server side
}
verify(mockServerInterceptor).interceptCall(
ArgumentMatchers.<ServerCall<HelloRequest, HelloReply>>any(),
metadataCaptor.capture(),
ArgumentMatchers.<ServerCallHandler<HelloRequest, HelloReply>>any());
assertEquals(
"customRequestValue",
metadataCaptor.getValue().get(HeaderClientInterceptor.CUSTOM_HEADER_KEY));
}
@Before
public void setUp() throws Exception {
grpcServerRule
.getServiceRegistry()
.addService(
ServerInterceptors.intercept(greeterServiceImpl, injectCacheControlInterceptor));
grpcServerRule.getServiceRegistry().addService(anotherGreeterServiceImpl);
baseChannel = grpcServerRule.getChannel();
SafeMethodCachingInterceptor interceptor =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptor);
}
@Test
public void invalidResponseMaxAge_usesDefault() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
cacheControlDirectives.add("max-age=-10");
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertEquals(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
@Test
public void afterDefaultMaxAge_cacheEntryInvalidated() throws Exception {
SafeMethodCachingInterceptor interceptorWithCustomMaxAge =
SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache, 1);
channelToUse = ClientInterceptors.intercept(baseChannel, interceptorWithCustomMaxAge);
HelloReply reply1 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
HelloReply reply2 =
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message);
assertSame(reply1, reply2);
// Wait for cache entry to expire
sleepAtLeast(1001);
assertNotEquals(
reply1,
ClientCalls.blockingUnaryCall(
channelToUse, safeGreeterSayHelloMethod, CallOptions.DEFAULT, message));
Truth.assertThat(cache.removedKeys).hasSize(1);
assertEquals(
new SafeMethodCachingInterceptor.Key(
GreeterGrpc.getSayHelloMethod().getFullMethodName(), message),
cache.removedKeys.get(0));
}
@Before
public void setUp() throws Exception {
SimpleServiceGrpc.SimpleServiceImplBase simpleServiceImpl =
new SimpleServiceGrpc.SimpleServiceImplBase() {
@Override
public void unaryRpc(
SimpleRequest request, StreamObserver<SimpleResponse> responseObserver) {
for (Map.Entry<String, Double> entry : applicationMetrics.entrySet()) {
CallMetricRecorder.getCurrent().recordCallMetric(entry.getKey(), entry.getValue());
}
SimpleResponse response =
SimpleResponse.newBuilder().setResponseMessage("Simple response").build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
ServerInterceptor metricReportingServerInterceptor = new OrcaMetricReportingServerInterceptor();
String serverName = InProcessServerBuilder.generateName();
grpcCleanupRule.register(
InProcessServerBuilder
.forName(serverName)
.directExecutor()
.addService(
ServerInterceptors.intercept(simpleServiceImpl, metricReportingServerInterceptor))
.build().start());
ManagedChannel baseChannel =
grpcCleanupRule.register(InProcessChannelBuilder.forName(serverName).build());
channelToUse =
ClientInterceptors.intercept(
baseChannel, new TrailersCapturingClientInterceptor(trailersCapture));
}