
To begin with, Spring GRPC is a framework that allows you to build microservices using gRPC, a high-performance RPC framework.
First, you need to add the necessary dependencies to your project, including spring-boot-starter-grpc and io.grpc:grpc-netty.
Spring GRPC provides a simple way to define services using the @GrpcService annotation.
You can then use the gRPC protocol buffer compiler to generate the necessary code for your services.
Expand your knowledge: Azure Cloud Adoption Framework Handbook
Getting Started
To get started with Spring gRPC, head over to the Spring Initializr and select the gRPC dependency. This will give you a basic project setup to work with.
You can run the sample project in the samples directory using mvn spring-boot:run or gradle bootRun. This will give you a working service to experiment with.
To define a gRPC service, create a .proto service definition file in the src/main/proto directory. For example, you can create a file called hello.proto with the following contents:
❗ IMPORTANT: Be sure to change the java_package to the one you chose in Spring Initializr.
On a similar theme: Jupyter Notebook Azure
Two new folders will be generated containing the source code for the stubs: target/generated-sources/protobuf/grpc-java and target/generated-sources/protobuf/java for Maven, or build/generated/source/proto/main/grpc and build/generated/source/proto/main/java for Gradle.
You may need to instruct your IDE to mark them as source roots. In IntelliJ IDEA, right-click the folder and choose Mark Directory As -> Generated Source Root. Eclipse or VSCode will add them automatically for you.
Now you can implement a service based on the generated stubs. You can try it out using a gRPC client like grpcurl.
Check this out: Grpc Java
Spring Boot Starter
The Spring Boot Starter is a crucial part of getting started with gRPC in a Spring Boot application. It makes it easy to get started with gRPC in a Spring Boot application with autoconfiguration and configuration properties.
You can add the Spring Boot Starter to your project by selecting the gRPC dependency in the Spring Initializr. From there, you can open the project in your IDE and start working with gRPC. The Spring Boot Starter will take care of the underlying configuration, allowing you to focus on implementing your gRPC service.
The Spring Boot Starter also includes a Spring Boot Web dependency for REST controller support.
Check this out: Elasticsearch in Spring Boot
Add Dependencies
To add dependencies to your Spring Boot project, you'll need to include the Spring Boot Starter for basic application setup. This will provide the foundation for your project.
The Spring Boot Starter for gRPC includes several dependencies, such as Spring Boot Web for REST controller support and gRPC libraries for server and client implementation. These dependencies are essential for building a gRPC application with Spring Boot.
Here are the specific dependencies you'll need to add to your pom.xml file:
- Spring Boot Starter for basic application setup.
- Spring Boot Web for REST controller support.
- gRPC libraries for server and client implementation.
- Protobuf for serialization and deserialization.
For Maven users, you can add these dependencies to your pom.xml file by following the example in the Spring gRPC documentation.
Native in Servlet Container
In a Spring Boot application, you can run a native gRPC server inside a web application on a different port.
This is possible without including the grpc-servlet-jakarta dependency on your classpath.
To achieve this, simply don't include the spring-grpc-server-web-spring-boot-starter dependency, or set spring.grpc.server.servlet.enabled=false in your application configuration if you need to be explicit.
A native gRPC server will run happily inside a web application if you follow these steps.
Additional reading: Websocket Spring Boot
Service Configuration
You can configure a service to use server interceptors in several ways.
To add a server interceptor to a single service, simply register a server interceptor bean and annotate your BindableService bean with @GrpcService, specifying the interceptor using either the interceptors or interceptorNames attribute.
The interceptors are ordered according to their position in the attribute list, with entries in the interceptors list preceding entries in the interceptorNames list.
Here's an example of how to apply a per-service interceptor to a service:
By default, global interceptors are applied first, followed by per-service interceptors in their sorted order. However, you can change this behavior by setting the blendWithGlobalInterceptors attribute on the @GrpcService annotation to "true", which combines all interceptors and sorts them according to their bean natural ordering.
Per-Service
To add a server interceptor to a single service, you can register a server interceptor bean and annotate your BindableService bean with @GrpcService, specifying the interceptor using either the interceptors or interceptorNames attribute.

The interceptors are ordered according to their position in the attribute list. If you're using both interceptors and interceptorNames, the former entries precede the latter.
In the per-service configuration, you can specify the interceptor to be applied to a single service. For example, if you have a service called myService and you want to apply the myServerInterceptor, you can do so by annotating the myService bean with @GrpcService, specifying the interceptor using the interceptors or interceptorNames attribute.
Here's a summary of the per-service configuration:
If you're using both global and per-service interceptors, the global interceptors are applied first, followed by the per-service interceptors. However, you can change this behavior by setting the blendWithGlobalInterceptors attribute to "true", which combines the interceptors and sorts them according to their bean natural ordering.
Exception Handling
Exception handling is a crucial aspect of service configuration in Spring gRPC. To handle exceptions consistently, you can add beans of type GrpcExceptionHandler to your application context.
These exception handlers can be used to handle exceptions of a specific type or all exceptions. They can return null for exceptions they don't support.
To get started, you'll need to add the necessary beans to your application context. This will enable the autoconfigured exception handler to take care of exception handling for you.
By using GrpcExceptionHandler beans, you can provide a consistent way to handle exceptions thrown by your services. This makes it easier to manage and debug your application.
Security
To secure individual gRPC methods, you can add the @PreAuthorize annotation to the method definition. This allows you to specify which roles have access to the method.
You can also configure security using the usual HttpSecurity configuration, where you can specify which users have access to which methods. For example, you can allow access to the Simple/SayHello method to users with the USER role.
OAuth2 Resource Server is also supported, and can be enabled by adding the spring-security-oauth2-resource-server dependency to your classpath. This allows Spring gRPC to automatically configure an OAuth2 resource server.
Related reading: Grpc Security
Securing Individual Methods

Securing individual gRPC methods can be done by adding the @PreAuthorize annotation to the method definition, allowing you to control access to specific methods based on user roles.
You can also configure security using the usual HttpSecurity configuration, where you can specify which methods are accessible to users with certain roles.
For example, you can allow access to the Simple/SayHello method to users with the USER role, and to the Simple/StreamHello method to users with the ADMIN role.
This approach allows you to fine-tune access control for individual methods, giving you more flexibility in managing your application's security.
You can also disallow access to all other methods unless authenticated, ensuring that only authorized users can access sensitive methods.
OAuth2 Resource
You can automatically configure an OAuth2 resource server in Spring gRPC if you have the spring-security-oauth2-resource-server dependency on the classpath.
This allows you to easily add OAuth2 security to your gRPC services.
There are two choices for token types: JWT and opaque tokens.
For JWT, you need to set up either the JWK Set or OIDC Issuer URI.
The JWK Set URI is set via spring.security.oauth2.resourceserver.jwt.jwk-set-uri.
You'll also need the spring-security-oauth2-jose dependency on the classpath for JWT decoding.
For opaque tokens, it works exactly the same as with a regular web application.
You can configure it with the same application properties.
Filtering
You can control which interceptors are applied to your gRPC servers by using a ServerInterceptorFilter bean. This is especially useful when you want to prevent sensitive data from being exposed.
The ExtraThingsInterceptor interceptor can be prevented from being applied to servers created by a specific server factory by registering a ServerInterceptorFilter bean. This is automatically picked up by the InProcessGrpcServerFactory.
To add a ServerInterceptorFilter to other server factories, you'll need to provide a GrpcServerFactoryCustomizer that includes the filter.
By using a ServerInterceptorFilter, you can ensure that only authorized interceptors are applied to your gRPC servers, reducing the risk of data breaches and other security threats.
Observability
Observability is crucial for any distributed system, and Spring gRPC makes it easy to achieve. You can add Spring Boot actuators to your project for auto-configured observability.
To get started, you'll need to add Spring Boot actuators to your project. This will provide trace logging and metrics when you connect to the server.
The grpc-tomcat sample in the Spring gRPC repository shows how to do it. This sample demonstrates how to set up observability in a Spring gRPC application.
The Spring integration collects metrics defined in the gRFC A66 specification. This allows you to easily collect and expose metrics from your gRPC services.
You can configure your monitoring backend, such as Prometheus, to scrape these metrics from the URL you set on your gRPC/Spring microservices. For example, you can use the /actuator/prometheus endpoint.
Google Cloud's Managed Service for Prometheus makes it easy to set up and manage your Prometheus metrics. You can use this service to scrape metrics from your gRPC/Spring microservices and gain valuable insights into your system's performance.
On a similar theme: Devtools in Spring Boot
Testing
Testing your gRPC server in a Spring Boot application is crucial for ensuring it works as expected. To do this, you include spring-grpc-test in your project.
You can enable the in-process server by setting spring.grpc.test.inprocess.enabled to true or by adding the @AutoConfigureInProcessTransport annotation to your @SpringBootTest class. This allows clients to connect to the server without needing a network port.
The in-process server replaces the regular server and channel factories, such as Netty, when run in test mode. This means you can test your gRPC server without the overhead of a network connection.
GPRC
To create a gRPC server, you need to provide one or more beans of type BindableService. This can be done by creating a @Bean of type BindableService, such as the SimpleImplBase class generated from your Protobuf file.
You can also use pre-built BindableServices, like the gRPC Reflection or gRPC Health services, by simply adding them to your application. To activate your own BindableService, simply add a Spring @Service annotation to the implementation class and have it picked up by the @ComponentScan in your Spring Boot application.
To create a gRPC client, use the Spring Boot starter and inject a bean of type GrpcChannelFactory. You can then use it to create a gRPC channel and bind to a service, such as the SimpleGrpc service on a local server. The default GrpcChannelFactory implementation can also create a "named" channel, which you can configure in the application.properties file.
Check this out: Grpc Channel
GPRC
GPRC is a powerful tool for building high-performance, scalable, and interoperable services. It's a great choice for developers who want to create efficient and reliable applications.
To create a simple gRPC client, you can use the Spring Boot starter and inject a bean of type GrpcChannelFactory. This will allow you to create a gRPC channel and bind to a service.
The default GrpcChannelFactory implementation can also create a "named" channel, which you can then use to extract the configuration to connect to the server. For example, you can configure a default named channel in the application.properties file.
Consider reading: When to Use Grpc
You can run an in-process server by including the io.grpc.grpc-inprocess dependency on your classpath and specifying the spring.grpc.server.inprocess.name property. This will allow you to create an in-process server without listening on a network port.
Annotate a field of your grpc client stub with @GrpcClient(serverName) to specify the server to connect to. This will allow you to send queries to your server just like a regular gRPC client.
Spring Boot is a popular framework for building Java applications, and combining it with gRPC allows developers to create high-performance, scalable, and interoperable services. With Spring Boot's auto-configuration and dependency injection, integrating gRPC becomes straightforward.
Here are some features of the gRPC library:
- Automatically configures and runs the gRPC server with your @GrpcService implementations
- Automatically creates and manages your grpc channels and stubs with @GrpcClient
- Supports other grpc-java flavors (e.g. Reactive gRPC, grpc-kotlin, ...)
- Supports Spring-Security
- Supports Spring Cloud
- Supports Spring Sleuth as distributed tracing solution
- Supports global and custom gRPC server/client interceptors
- Automatic metric support (micrometer/actuator based)
- Also works with (non-shaded) grpc-netty
You can configure common features of the server by using the grpc.server prefix in application.properties or application.yml. For instance, to set the port to listen on, use spring.grpc.server.port (defaults to 9090).
Native Images
Native images are supported for gRPC servers and clients. You can use them to build high-performance applications.
You can build native images in the normal Spring Boot way for your build tool, whether it's Maven or Gradle.
Service Filtering
Service Filtering is a powerful feature that lets you decide which services are bound to which server factories.
All available BindableService beans are bound to all running gRPC servers by default.
You can register a ServerServiceDefinitionFilter bean to customize this behavior.
This filter can be used to prevent certain services from being bound to a specific server factory.
For example, you can use the filter to prevent the "health" and "reflection" service from being bound to the server created by the InProcessGrpcServerFactory.
The InProcessGrpcServerFactory picks up the ServerServiceDefinitionFilter automatically, so you don't need to do anything extra.
Any other server factory, however, will require you to provide a GrpcServerFactoryCustomizer to add the filter.
See what others are reading: Azure Communication Services
Protobuf
Protobuf is a secret code that helps computers talk to each other using very short and simple messages. It turns big messages into small codes that are easy and quick for computers to understand and send.
This code is generated from a .proto file, which can be used to create Java classes using a Maven command. Running this command will generate the GreeterGrpc and related classes in the target/generated-sources directory.
Protobuf is widely used in systems where efficiency and cross-platform support are crucial, like in microservices architectures and cloud-native applications.
You might like: Spring Command Line Runner
Generate Java Classes
Generating Java classes from a .proto file is a crucial step in the Protobuf process. To do this, you'll need to run a Maven command.
The command to generate Java classes from a .proto file is run in the terminal or command prompt. This will generate the necessary classes in the target/generated-sources directory.
The generated classes will include the GreeterGrpc and related classes, which are essential for building a Protobuf application.
Additional reading: Distributed File System for Cloud
What is Protobuf?
Protobuf is like a secret code that helps computers talk to each other using very short and simple messages.
It turns big messages into small codes that are easy and quick for computers to understand and send.
Imagine you and your friend make a list of lunch items, and instead of saying the full names like “sandwich” or “banana,” you use numbers like 1 for sandwich and 2 for banana.
This helps reduce the size of the messages and makes communication faster and more efficient.
Protobuf uses a list of numbers to represent messages, similar to how you and your friend used numbers to represent lunch items.
See what others are reading: Grpc vs Protobuf
Spring
The Spring gRPC project provides a Spring-friendly API and abstractions for developing gRPC applications.
The core library makes it easy to work with gRPC and dependency injection.
There is a Spring Boot starter that makes it easy to get started with gRPC in a Spring Boot application.
For further information, go to the Spring gRPC reference documentation.
To get started, generate the project and unzip the downloaded result.
Featured Images: pexels.com

