A real-world example of bidirectional streaming using gRPC in a Spring Boot application with a REST wrapper for client interaction.
- Java 11
- Spring Boot 2.7.x
- gRPC (1.54.0)
- Protocol Buffers (proto3)
- Maven
- WebFlux + Server-Sent Events (SSE) for REST integration
β Code Repository LinkΒ
LinkΒ -Β grpc-bidirectional-chat-server-client
1. Start gRPC Server
- cd grpc-bidirectional-chat mvn clean install mvn spring-boot:run
2. Start REST Clien
- cd grpc-bidirectional-chat-client mvn clean install mvn spring-boot:run
3. Upload a File via REST
- curl -X POST "http://localhost:8081/chat?sender=Alice&message=Hello"
β Project Structure
Server:Β grpc-bidirectional-chat
- grpc-bidirectional-chat/ βββ pom.xml βββ src β βββ main β β βββ java/com/example/grpc/ β β β βββ ChatServiceImpl.java # gRPC service impl β β β βββ GrpcServerApplication.java # Spring Boot entry β β βββ resources/ β β βββ application.yml β βββ proto/ β βββ chat.proto # gRPC contract
Client:Β grpc-bidirectional-chat-client
- grpc-bidirectional-chat-client/ βββ pom.xml βββ src β βββ main β β βββ java/com/example/grpc/ β β β βββ ChatController.java # REST controller β β β βββ GrpcClientApplication.java # Spring Boot entry β β βββ resources/ β β βββ application.yml
π§ Class Responsibilities
π’Β Server
-
GrpcServerApplication.java
β Main Spring Boot entry point for the gRPC server.
-
ChatServiceImpl.java
β Implements the gRPC ChatService
and handles bidirectional chat streams.
GrpcServerApplication.java
β Main Spring Boot entry point for the gRPC server.
ChatServiceImpl.java
β Implements the gRPC ChatService
and handles bidirectional chat streams.
π΅ Client
-
GrpcClientApplication.java
β Main Spring Boot entry for the client REST API wrapper.
-
ChatController.java
β Exposes a /chat
REST endpoint to initiate gRPC bidirectional streaming using stub.
GrpcClientApplication.java
β Main Spring Boot entry for the client REST API wrapper.
ChatController.java
β Exposes a /chat
REST endpoint to initiate gRPC bidirectional streaming using stub.
𧬠Proto FileΒ
- syntax = "proto3"; option java_multiple_files = true; option java_package = "com.example.grpc"; option java_outer_classname = "ChatProto"; service ChatService { rpc chatStream (stream ChatMessage) returns (stream ChatMessage); } message ChatMessage { string sender = 1; string message = 2; int64 timestamp = 3; }
- [POST /chat?sender=Alice&message=Hello] | v +-------------------+ | Spring Controller | +-------------------+ | v +------------------------+ | gRPC Async Stub (Client) | +------------------------+ | v +------------------------+ | gRPC Server Impl | | - ChatServiceImpl | +------------------------+ | v [Responds back via StreamObserver]
When to Use gRPC bidirectional Streaming