io.grpc.ClientInterceptors Java Examples
The following examples show how to use
io.grpc.ClientInterceptors.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractChannelFactory.java From grpc-spring-boot-starter with MIT License | 6 votes |
@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); }
Example #2
Source File: GoogleCredentialsInterceptor.java From Saiy-PS with GNU Affero General Public License v3.0 | 6 votes |
@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); } }; }
Example #3
Source File: SpeechService.java From black-mirror with MIT License | 6 votes |
@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); } }; }
Example #4
Source File: AbstractChannelFactory.java From grpc-spring-boot-starter with MIT License | 6 votes |
@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); }
Example #5
Source File: SpeechService.java From android-docs-samples with Apache License 2.0 | 6 votes |
@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); } }; }
Example #6
Source File: LoggingInterceptorTest.java From bazel with Apache License 2.0 | 6 votes |
@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); }
Example #7
Source File: AbelanaClient.java From abelana with Apache License 2.0 | 6 votes |
/** * 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; }
Example #8
Source File: Main.java From cloud-pubsub-samples-java with Apache License 2.0 | 5 votes |
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()); } }
Example #9
Source File: ConnectorUtils.java From pubsub with Apache License 2.0 | 5 votes |
/** 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); }
Example #10
Source File: PubsubGrpcClient.java From beam with Apache License 2.0 | 5 votes |
/** 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); }
Example #11
Source File: HelloWorldClient.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** 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); }
Example #12
Source File: BookstoreClient.java From java-docs-samples with Apache License 2.0 | 5 votes |
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); }
Example #13
Source File: CaseController.java From skywalking with Apache License 2.0 | 5 votes |
@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())); }
Example #14
Source File: BaseITTracingServerInterceptor.java From brave with Apache License 2.0 | 5 votes |
Channel clientWithB3SingleHeader(TraceContext parent) { return ClientInterceptors.intercept(client, 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) { headers.put(Key.of("b3", ASCII_STRING_MARSHALLER), B3SingleFormat.writeB3SingleFormat(parent)); super.start(responseListener, headers); } }; } }); }
Example #15
Source File: CustomHeaderClient.java From grpc-java with Apache License 2.0 | 5 votes |
/** * 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); }
Example #16
Source File: HeaderClientInterceptorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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)); }
Example #17
Source File: SafeMethodCachingInterceptorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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); }
Example #18
Source File: SafeMethodCachingInterceptorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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)); }
Example #19
Source File: SafeMethodCachingInterceptorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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)); }
Example #20
Source File: OrcaMetricReportingServerInterceptorTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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)); }
Example #21
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 5 votes |
/** Sends a cacheable unary rpc using GET. Requires that the server is behind a caching proxy. */ public void cacheableUnary() { // THIS TEST IS BROKEN. Enabling safe just on the MethodDescriptor does nothing by itself. This // test would need to enable GET on the channel. // 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); // THIS TEST IS BROKEN. See comment at start of method. }
Example #22
Source File: ManagedChannelImplTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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()); }
Example #23
Source File: CustomHeaderClient.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** * 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); }
Example #24
Source File: TracedClient.java From java-grpc with Apache License 2.0 | 5 votes |
TracedClient( ManagedChannel channel, long deadline, String compression, ClientInterceptor... interceptors) { blockingStub = GreeterGrpc.newBlockingStub(ClientInterceptors.intercept(channel, interceptors)) .withDeadlineAfter(deadline, TimeUnit.MILLISECONDS) .withCompression(compression); }
Example #25
Source File: HeaderClientInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@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)); }
Example #26
Source File: SafeMethodCachingInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@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); }
Example #27
Source File: SafeMethodCachingInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@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)); }
Example #28
Source File: SafeMethodCachingInterceptorTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
@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)); }
Example #29
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** 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); }
Example #30
Source File: CustomHeaderClient.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** * 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); }