Skip to main content

Extension Points

ClientInterceptor

io.grpc.ClientInterceptor is an interceptor to intercept the lifecycle of a gRPC call on the client side.

Register a ClientInterceptor for all gRPC stubs:

@Component
public class LoggingClientInterceptor implements ClientInterceptor {
private static final Logger log = LoggerFactory.getLogger(LoggingClientInterceptor.class);

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new ForwardingClientCall.SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void sendMessage(ReqT message) {
log.info("Sending message: {}", message);
super.sendMessage(message);
}
};
}
}

Multiple ClientInterceptor will be called in the order defined by the Spring Bean's order, from smallest to largest.

GrpcChannelCustomizer

GrpcChannelCustomizer customize the Channel before it is created.

Register a GrpcChannelCustomizer to set the retry attempts for the gRPC channels:

@Component
public class RetryGrpcChannelCustomizer implements GrpcChannelCustomizer {
@Override
public void customize(GrpcClientProperties.Channel channelConfig, ManagedChannelBuilder<?> channelBuilder) {
channelBuilder.enableRetry().maxRetryAttempts(3);
}
}

Multiple GrpcChannelCustomizer will be called in the order defined by the Spring Bean's order, from smallest to largest.

GrpcClientBeanDefinitionHandler

Starting from 3.4.3.1, GrpcClientBeanDefinitionHandler is used to post-process BeanDefinition before the gRPC client bean is registered.

You can set beanDefinitionHandler by @EnableGrpcClient or configuring grpc.client.bean-definition-handler. If both are set, the one set by @EnableGrpcClient will be used.

If you want only blocking stub to be registered:

@EnableGrpcClients(beanDefinitionHandler = GrpcClientBeanDefinitionHandler.Blocking.class)

The framework provides some built-in GrpcClientBeanDefinitionHandler implementations:

  • GrpcClientBeanDefinitionHandler.Default: Register all stubs.
  • GrpcClientBeanDefinitionHandler.Blocking: Only register blocking stub.
  • GrpcClientBeanDefinitionHandler.Future: Only register future stub.
  • GrpcClientBeanDefinitionHandler.Async: Only register async stub.

Deep Customization

If you're not happy with the autoconfigured gRPC client bean, you can configure it using the Spring original approach (@Bean).

If you manually create the gRPC client bean, the autoconfigured gRPC client bean will not be created.

@Configuration
class GrpcClientConfiguration {
@Bean
public SimpleServiceGrpc.SimpleServiceBlockingStub simpleServiceBlockingStub() {
var channel = ManagedChannelBuilder.forAddress("localhost", 9090)
.usePlaintext()
.build();
return SimpleServiceGrpc.newBlockingStub(channel);
}
}