Spring gRPC Documentation
repository·main·Indexed 19 days ago
https://github.com/spring-projects/spring-grpcSpring gRPC provides a Spring-friendly API and abstractions for developing gRPC applications, featuring a core library for dependency injection and a Spring Boot starter for autoconfiguration. It supports gRPC server and client implementation, named channel configuration via application.properties, OAuth2 authentication, and native image support via GraalVM.
What's inside Spring gRPC
- Spring gRPC is a project designed to streamline the development of gRPC applications within the Spring ecosystem. It provides abstractions and integrations for both gRPC servers and gRPC clients, allowing developers to build high-performance, type-safe communication layers using Spring's programming model.
Overview of Spring gRPC
mainSpring gRPC provides a Spring-friendly API and abstractions for developing gRPC applications. It consists of two main components:
- Core Library: Provides abstractions to make working with gRPC and dependency injection seamless.
- Spring Boot Starter: Enables rapid development in Spring Boot applications through autoconfiguration and dedicated configuration properties.
Filter which services are bound to a gRPC server
mainBy default, all
BindableServicebeans are bound to all running gRPC servers. You can control this by registering aServerServiceDefinitionFilterbean.For
InProcessGrpcServerFactory, the filter is applied automatically. For other factories (likeNettyGrpcServerFactory), you must provide aGrpcServerFactoryCustomizerto register the filter.// 1. Define the filter @Bean ServerServiceDefinitionFilter myServiceFilter() { return (serviceDefinition, __) -> !Set.of(HealthGrpc.SERVICE_NAME, ServerReflectionGrpc.SERVICE_NAME) .contains(serviceDefinition.getServiceDescriptor().getName()); } // 2. Apply it via a customizer (required for Netty) @Bean GrpcServerFactoryCustomizer myServerFactoryCustomizer(ServerServiceDefinitionFilter myServiceFilter) { return factory -> { if (factory instanceof NettyGrpcServerFactory nettyServerFactory) { nettyServerFactory.setServiceFilter(myServiceFilter); } }; }Run gRPC in a Servlet Container
mainYou can run a gRPC server inside any servlet container (like Tomcat or Jetty).
Requirements & Behavior:
- HTTP/2: You must enable HTTP/2 on the servlet container using its native configuration. Spring Boot provides auto-configuration for Tomcat and Jetty.
- Path Mapping: The servlet maps HTTP POST requests to service paths using the pattern
/<service-name>/*. - Limitations: The servlet-based server has fewer configuration options than native builders because the container manages the network layer. Some
ServerBuilderCustomizerfeatures may throw exceptions at runtime. - Native Coexistence: A native gRPC server (e.g., Netty) can run alongside a servlet container on a different port.
Add Client Interceptors
mainInterceptors can be applied at three levels:
- Global: Register a bean annotated with
@GlobalClientInterceptor. These are applied to all channels in@Ordersequence. - Per-Channel: Pass interceptors via
ChannelBuilderOptions.withInterceptors(List.of(...))when creating a channel. These are applied after global interceptors. - Blended: By default, global interceptors run first, then per-channel interceptors. If you set
ChannelBuilderOptions.withInterceptorsMerge(true), all interceptors (global and per-channel) are combined and sorted together by their@Order.
Note: For proper merging, per-channel interceptors should be beans with
@Orderor implementOrdered.// Global interceptor registration @Bean @Order(100) @GlobalClientInterceptor ClientInterceptor globalLoggingInterceptor() { return new LoggingInterceptor(); } // Per-channel interceptor registration @Bean SimpleGrpc.SimpleBlockingStub stub(GrpcChannelFactory channelFactory) { ClientInterceptor interceptor1 = getChannelInterceptor1(); ChannelBuilderOptions options = ChannelBuilderOptions.defaults() .withInterceptors(List.of(interceptor1)); ManagedChannel channel = channelFactory.createChannel("localhost", options); return SimpleGrpc.newBlockingStub(channel); }- Global: Register a bean annotated with
Understand Maven Parent overrides in this project
mainThis project uses empty overrides for
<license>and<developers>elements in its POM file. This is done to prevent unwanted inheritance of these specific elements from the parent POM.Note: If you manually change the parent of this project and wish to inherit license and developer information, you must remove these empty overrides from your project's POM.
Understand Gradle Toolchain support with Native Build Tools
mainWhen using Native Build Tools for native image compilation, be aware that toolchain support is disabled by default. In this mode, native image compilation is performed using the specific JDK that is used to execute Gradle, rather than a configured toolchain JDK.Handle Maven Parent overrides for license and developer metadata
mainThis project uses empty overrides for
<license>and<developers>in the project POM to prevent unwanted inheritance from the parent POM.If you switch to a different parent POM and wish to inherit these elements, you must manually remove these empty overrides from your project's POM file.
Automatic Configuration of gRPC Clients (v0.5.0)
mainStarting from version 0.5.0, you can use@EnableGrpcClientsand the nested@GrpcClientannotations to automatically configure gRPC clients. You can use@GrpcClientto either explicitly enumerate stub types or to scan a base package for stubs.Quickstart: Create a working Spring gRPC service
mainTo quickly set up a Spring gRPC service, follow these steps:
- Initialize Project: Use Spring Initializr and select the
gRPCdependency. - Define Proto: Create
src/main/proto/hello.proto. Ensure thejava_packagematches your project's package name. - Generate Stubs: Run
./mvnw clean package(Maven) or./gradlew build(Gradle) to generate Java source code from your.protofile. - Implement Service: Create a class annotated with
@Servicethat extends the generatedImplBaseclass. - Run: Execute the application using
./mvnw spring-boot:runor./gradlew bootRun.
Generated Source Locations:
- Maven:
target/generated-sources/protobuf/grpc-javaandtarget/generated-sources/protobuf/java - Gradle:
build/generated/source/proto/main/grpcandbuild/generated/source/proto/main/java
Note: You may need to manually mark these folders as 'Generated Source Roots' in your IDE (e.g., IntelliJ IDEA).
syntax = "proto3"; option java_multiple_files = true; option java_package = "<your-package-name-goes-here>.proto"; option java_outer_classname = "HelloWorldProto"; service Simple { rpc SayHello(HelloRequest) returns (HelloReply) {} rpc StreamHello(HelloRequest) returns (stream HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }- Initialize Project: Use Spring Initializr and select the
Quickstart: Create a Spring gRPC service
mainTo quickly set up a working gRPC service with Spring gRPC:
- Generate Project: Use Spring Initializr and select the
gRPCdependency. - Define Proto: Create
src/main/proto/hello.proto. Ensure thejava_packagematches your project's package name. - Generate Stubs: Run
./mvnw clean package(Maven) or./gradlew build(Gradle).- Maven paths:
target/generated-sources/protobuf/grpc-javaandtarget/generated-sources/protobuf/java. - Gradle paths:
build/generated/source/proto/main/grpcandbuild/generated/source/proto/main/java. - Note: You may need to mark these as 'Generated Source Roots' in your IDE.
- Maven paths:
- Implement Service: Create a class annotated with
@Servicethat extends the generatedImplBaseclass. - Run: Use
./mvnw spring-boot:runor./gradlew bootRun.
syntax = "proto3"; option java_multiple_files = true; option java_package = "<your-package-name-goes-here>.proto"; option java_outer_classname = "HelloWorldProto"; service Simple { rpc SayHello(HelloRequest) returns (HelloReply) {} rpc StreamHello(HelloRequest) returns (stream HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; }- Generate Project: Use Spring Initializr and select the
Build Native Images for the gRPC Sample
mainTo build a native image for this gRPC sample, refer to the specific guide for your build tool:
- For Gradle: See Native Image with Gradle
- For Maven: See Native Image with Maven