Skip to content

pedroid999/test-grpc

Repository files navigation

Spring Boot gRPC Demo Project

This project demonstrates how to implement a gRPC service in Spring Boot with a declarative client similar to Feign for REST services. It's designed for learning purposes and includes comprehensive documentation to help developers understand gRPC concepts and implementation.

Table of Contents

Project Overview

This project demonstrates a complete gRPC implementation in Spring Boot, featuring:

  • Protocol Buffer definitions for a User service
  • A Spring Boot gRPC server implementation
  • A declarative gRPC client (similar to Feign for REST)
  • A demo application showcasing the client usage

The application implements a simple User management service with CRUD operations, demonstrating how to structure a gRPC-based microservice architecture.

Project Structure

The project is organized as a multi-module Maven project:

  • proto: Contains Protocol Buffer definitions and generates Java code
  • grpc-server: Implements the gRPC server with business logic
  • grpc-client: Provides a declarative client interface for the gRPC service
  • grpc-demo-app: Demonstrates the usage of the gRPC client

Key Features

  • Declarative gRPC Client: Similar to Feign for REST, providing a simple interface for gRPC services
  • Comprehensive Documentation: Detailed explanations and comments throughout the code
  • Clean Architecture: Separation of concerns with a multi-module structure
  • Error Handling: Proper error handling and exception propagation
  • Integration with Spring Boot: Seamless integration with Spring Boot ecosystem

Getting Started

Prerequisites

  • Java 17 or higher
  • Maven 3.6 or higher
  • Git

Building the Project

  1. Clone the repository:

    git clone https://github.com/yourusername/grpc-demo.git
    cd grpc-demo
  2. Build the project:

    mvn clean install

Running the Application

  1. Start the gRPC server:

    cd grpc-server
    mvn spring-boot:run
  2. In a new terminal, start the demo application:

    cd grpc-demo-app
    mvn spring-boot:run
  3. The server will be running on port 9090 (gRPC) and 8080 (HTTP)

  4. The demo application will be running on port 8081

Understanding gRPC

What is gRPC?

gRPC is a high-performance, open-source universal RPC (Remote Procedure Call) framework developed by Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, load balancing, and more.

Key advantages of gRPC include:

  • Performance: Significantly faster than traditional REST APIs due to HTTP/2 and binary serialization
  • Strong Typing: Contract-first approach with Protocol Buffers
  • Code Generation: Automatic client and server code generation
  • Bi-directional Streaming: Support for streaming in both directions
  • Language Agnostic: Support for multiple programming languages

Protocol Buffers

Protocol Buffers (protobuf) is Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data. It's smaller, faster, and simpler than XML or JSON.

Example from this project:

syntax = "proto3";

service UserService {
  rpc GetUser (GetUserRequest) returns (UserResponse) {}
  // Other methods...
}

message GetUserRequest {
  int64 id = 1;
}

message UserResponse {
  int64 id = 1;
  string name = 2;
  string email = 3;
  int32 age = 4;
  // Other fields...
}

gRPC vs REST

Feature gRPC REST
Protocol HTTP/2 HTTP
Payload Protocol Buffers (binary) JSON/XML (text)
Contract Strict (proto files) Loose (OpenAPI/Swagger)
Code Generation Yes, built-in Requires additional tools
Streaming Bi-directional streaming Limited (WebSockets)
Browser Support Limited (requires proxy) Native
Learning Curve Steeper Gentler
Performance Higher Lower
Maturity Newer Well-established

Project Components

Proto Module

The proto module contains Protocol Buffer definitions for the gRPC service. It defines:

  • Service interfaces (methods that can be called remotely)
  • Request and response message types
  • Data structures

The Maven build process generates Java code from these definitions using the protobuf-maven-plugin.

gRPC Server

The grpc-server module implements the gRPC service defined in the proto module. It includes:

  • Entity Classes: JPA entities for data persistence
  • Repositories: Spring Data JPA repositories for database operations
  • Services: Business logic implementation
  • gRPC Service Implementation: The actual implementation of the gRPC service

Declarative gRPC Client

The grpc-client module provides a declarative client interface for the gRPC service, similar to Feign for REST services. It includes:

  • Client Interface: A simple Java interface defining the operations
  • Client Implementation: The implementation that handles the gRPC communication
  • Exception Handling: Custom exceptions for error handling

Example of the declarative client interface:

public interface UserClient {
    UserResponse getUser(Long id);
    UserResponse createUser(String name, String email, int age);
    List<UserResponse> listUsers(int page, int size);
    // Other methods...
}

Demo Application

The grpc-demo-app module demonstrates the usage of the gRPC client. It includes:

  • REST Controllers: Exposing the gRPC service as REST endpoints
  • DTOs: Data Transfer Objects for the REST API
  • Exception Handling: Proper error handling and status codes

Testing the Application

You can test the application using the following curl commands:

  1. Create a user:

    curl -X POST http://localhost:8081/api/users -H "Content-Type: application/json" -d '{"name":"John Doe","email":"[email protected]","age":30}'
  2. Get a user:

    curl http://localhost:8081/api/users/1
  3. List users:

    curl http://localhost:8081/api/users
  4. Update a user:

    curl -X PUT http://localhost:8081/api/users/1 -H "Content-Type: application/json" -d '{"name":"John Updated","email":"[email protected]","age":31}'
  5. Delete a user:

    curl -X DELETE http://localhost:8081/api/users/1

Best Practices

Protocol Buffer Design

  • Use a consistent naming convention
  • Keep messages focused and cohesive
  • Use appropriate field types
  • Consider backward compatibility
  • Use comments to document fields and messages

gRPC Service Implementation

  • Handle errors properly with appropriate status codes
  • Implement proper validation
  • Use interceptors for cross-cutting concerns
  • Consider timeouts and deadlines
  • Implement proper logging

Client Design

  • Make the client interface intuitive and simple
  • Handle errors gracefully
  • Implement proper retries and circuit breaking
  • Consider timeouts and deadlines
  • Provide clear documentation

Common Issues and Solutions

Connection Issues

Problem: Client cannot connect to the server. Solution: Check that the server is running and the port is correct. Ensure there are no firewall issues.

Serialization Errors

Problem: Errors related to serialization/deserialization. Solution: Ensure that the proto files are the same version on both client and server.

Performance Issues

Problem: Slow performance. Solution: Consider using streaming for large data sets, optimize message size, and ensure proper connection pooling.

Further Reading


License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • The gRPC team for creating an excellent framework
  • The Spring Boot team for their amazing work
  • All contributors to the open-source libraries used in this project

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages