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.
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);
}
}