类io.grpc.ClientInterceptors源码实例Demo

下面列出了怎么用io.grpc.ClientInterceptors的API类实例代码及写法,或者点击链接到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);
}
 
源代码2 项目: black-mirror   文件: SpeechService.java
@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);
        }
    };
}
 
源代码3 项目: Saiy-PS   文件: GoogleCredentialsInterceptor.java
@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);
}
 
源代码5 项目: android-docs-samples   文件: SpeechService.java
@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);
        }
    };
}
 
源代码6 项目: abelana   文件: AbelanaClient.java
/**
 * 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;
}
 
源代码7 项目: bazel   文件: LoggingInterceptorTest.java
@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);
}
 
源代码8 项目: grpc-nebula-java   文件: CustomHeaderClient.java
/**
 * 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));
}
 
源代码13 项目: grpc-nebula-java   文件: AbstractInteropTest.java
/** 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);
}
 
源代码14 项目: grpc-nebula-java   文件: CustomHeaderClient.java
/**
 * 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);
}
 
源代码15 项目: firebase-android-sdk   文件: GrpcClientModule.java
@Provides
@FirebaseAppScope
public InAppMessagingSdkServingBlockingStub providesInAppMessagingSdkServingStub(
    Channel channel, Metadata metadata) {
  return InAppMessagingSdkServingGrpc.newBlockingStub(
      ClientInterceptors.intercept(channel, MetadataUtils.newAttachHeadersInterceptor(metadata)));
}
 
源代码16 项目: firebase-android-sdk   文件: GrpcClientTest.java
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);
  inAppMessagingSdkServingBlockingStub =
      InAppMessagingSdkServingGrpc.newBlockingStub(
          ClientInterceptors.intercept(
              grpcServerRule.getChannel(),
              MetadataUtils.newAttachHeadersInterceptor(testMetadata)));
  grpcClient = new GrpcClient(inAppMessagingSdkServingBlockingStub);
}
 
源代码17 项目: java-grpc   文件: TracedClient.java
TracedClient(
    ManagedChannel channel,
    long deadline,
    String compression,
    ClientInterceptor... interceptors) {
  blockingStub =
      GreeterGrpc.newBlockingStub(ClientInterceptors.intercept(channel, interceptors))
          .withDeadlineAfter(deadline, TimeUnit.MILLISECONDS)
          .withCompression(compression);
}
 
源代码18 项目: concurrency-limits   文件: Driver.java
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));
}
 
源代码19 项目: pubsub   文件: ConnectorUtils.java
/** 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);
}
 
源代码20 项目: beam   文件: PubsubGrpcClient.java
/** 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);
}
 
源代码21 项目: java-docs-samples   文件: HelloWorldClient.java
/** 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);
}
 
源代码22 项目: java-docs-samples   文件: BookstoreClient.java
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);
}
 
源代码23 项目: skywalking   文件: CaseController.java
@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()));
}
 
源代码24 项目: cloud-pubsub-samples-java   文件: Main.java
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());
        }
    }
 
源代码25 项目: grpc-java   文件: CustomHeaderClient.java
/**
 * 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);
}
 
源代码26 项目: grpc-java   文件: HeaderClientInterceptorTest.java
@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));
}
 
 类所在包
 类方法
 同包方法