Spring Boot gRPC Example (2024) | TechGeekNext

Spring Boot gRPC Example (2024)

In this tutorial, we will learn how to implement gRPC with Spring Boot application.

Q: What is gRPC?
Ans:

gRPC is google Remote Procedure Call (gRPC) open source framework used to create scalable and quick APIs. It enables unary, client streaming, server streaming, or both client-server streaming communication between client and server applications. gRPC is built for the HTTP/2 protocol, which is lightweight and efficient in both transmitting and receiving data.

Create Spring Boot Project from Spring Initializer

Project Structure

Spring Boot gRPC Example

Maven Dependency

Add all of the dependencies listed below, as well as the build section from the pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.7</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.techgeeknext</groupId>
	<artifactId>Spring-Boot-GRPC-Example</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring-Boot-GRPC-Example</name>
	<description>Spring Boot GRPC Example</description>
	<properties>
		<java.version>1.8</java.version>
		<protobuf.version>3.17.3</protobuf.version>
		<protobuf-plugin.version>0.6.1</protobuf-plugin.version>
		<grpc.version>1.42.1</grpc.version>
	</properties>
	<dependencies>

		<dependency>
			<groupId>net.devh</groupId>
			<artifactId>grpc-server-spring-boot-starter</artifactId>
			<version>2.9.0.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>io.grpc</groupId>
			<artifactId>grpc-stub</artifactId>
			<version>${grpc.version}</version>
		</dependency>
		<dependency>
			<groupId>io.grpc</groupId>
			<artifactId>grpc-protobuf</artifactId>
			<version>${grpc.version}</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.11.2</version>
		</dependency>

	</dependencies>

	<build>
		<extensions>
			<extension>
				<groupId>kr.motd.maven</groupId>
				<artifactId>os-maven-plugin</artifactId>
				<version>1.7.0</version>
			</extension>
		</extensions>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.xolstice.maven.plugins</groupId>
				<artifactId>protobuf-maven-plugin</artifactId>
				<version>0.5.1</version>
				<configuration>
					<protocArtifact>
						com.google.protobuf:protoc:3.6.1:exe:${os.detected.classifier}
					</protocArtifact>
					<pluginId>grpc-java</pluginId>
					<pluginArtifact>
						io.grpc:protoc-gen-grpc-java:1.22.1:exe:${os.detected.classifier}
					</pluginArtifact>
					<protoSourceRoot>
						${basedir}/src/main/proto/
					</protoSourceRoot>
				</configuration>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
							<goal>compile-custom</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>

</project>

.proto

gRPC create rules by establishing a .proto file that must be followed by both the client and the server when exchanging data.

  1. Create the proto folder under src/main.
  2. Create the employee-service.proto file.
  3. Edit employee-service.proto, add EmployeeRequest and EmployeeResponse with its fields.
  4. Declare EmployeeService service.
syntax = "proto3";

import "constants/util.proto";

option java_multiple_files = true;
option java_package = "com.techgeeknext.employee";

message EmployeeRequest{
  string emp_id = 1;
}
message EmployeeResponse {
  string emp_id = 1;
  string name = 2;
  constants.Role role = 3;
}

service EmployeeService {
  rpc getEmployee(EmployeeRequest) returns (EmployeeResponse) {};
}

Employee Service Implementation

Create an Employee Service Implementation class in src/main/java and give the implementation for the employee-service.proto file's service declaration.

package com.techgeeknext.employee.service;

import com.techgeeknext.constants.Role;
import com.techgeeknext.employee.EmployeeRequest;
import com.techgeeknext.employee.EmployeeResponse;
import com.techgeeknext.employee.EmployeeServiceGrpc;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
public class EmployeeService extends EmployeeServiceGrpc.EmployeeServiceImplBase {

    /**
     * Unary operation to get the employee based on employee id
     * @param request
     * @param responseObserver
     */
    @Override
    public void getEmployee(EmployeeRequest request,
                            StreamObserver<EmployeeResponse> responseObserver) {

        //call repository to load the data from database
        //we have added static data for example
        EmployeeResponse empResp = EmployeeResponse
                .newBuilder()
                .setEmpId(request.getEmpId())
                .setName("abc")
                .setRole(Role.USER)
                .build();

        //set the response object
        responseObserver.onNext(empResp);

        //mark process is completed
        responseObserver.onCompleted();
    }
}

application.properties

Use any port or use default port to start the spring boot application.
grpc.server.port=9090

Test Spring Boot gRPC Example

  1. Start the Spring Boot Application by running spring-boot:run or by running main class.
  2. BloomRPC tool used to test gRPC service. Because gRPC is based on the HTTP/2 protocol, it will not work with HTTP/1 clients such as browsers or Postman. We can develop an adaptor service with a rest controller that consumes the gPRC services to execute on a browser or Postman.
    • Download the BloomRPC Tool. Run the BloomRPC-Setup-1.5.3.exe.
    Spring Boot Rest GRPC Example
    • Click on plus sign and provide the path of employee-service.proto file.
    • Change the port to 9090.
    • Click on the Green arrow to run the service.
    Spring Boot Rest GRPC Example

Download Source Code

The full source code for this article can be found on below.
Download it here - Spring Boot gRPC Example


Recommendation for Top Popular Post :