Spring Boot + C# gRPC Hello World Example
gRPC - Table of Contents
Spring Boot+ gRPC Hello World Example Spring Boot gRPC Server + C# gRPC Client Example Spring Boot 3 + gRPC - Types of gRPC Spring Boot 3 + gRPC Unary Example Spring Boot 3 + gRPC Server Streaming Example Spring Boot 3 + gRPC Client Streaming Example Spring Boot 3 + gRPC Bidirectional Streaming Example Spring Boot + gRPC Deadline Example Spring Boot + gRPC Error Handling Example Spring Boot + gRPC Error Handling - Using Trailer Metadata Spring Boot + gRPC Error Handling - Global Exception Handler Using GrpcAdvice
Video
This tutorial is explained in the below Youtube Video.Implementation
We will be making use of the Spring Boot gRPC server code that we had developed in previous tutorial. The maven project we will be creating is as follows -Start the spring boot project, the gRPC server gets started on port 9090.
C# Client Example
Start Visual Studio, and create a new console application.Create a folder name proto with the same proto files that we used in spring boot project.
syntax = "proto3"; import "Protos/constant/util.proto"; option java_multiple_files = true; option java_package = "com.javainuse.employee"; option csharp_namespace = "com.javainuse.employee"; message BookRequest{ string book_id = 1; } message BookResponse { string book_id = 1; string name = 2; constants.Type type = 3; } service BookService { rpc getBook(BookRequest) returns (BookResponse) {}; }The above proto file makes use of another proto file named util.proto where we define the enum Type.
syntax = "proto3"; package constants; option java_multiple_files = true; option java_package = "com.javainuse.constants"; option csharp_namespace = "com.javainuse.constants"; enum Type { FANTASY = 0; AUTOBIOGRAPHY = 1; HISTORY = 2; }Next to the console application we will be adding dependencies Manage NuGet Packages.
These dependencies are
- Google.Protobuf
- Grpc.Net.Client
- Grpc.Tools
Do the same for both proto files.
Next right click on the project and build it.
Next in the Program.cs file we will be making use of the gRPC client to consume the endpoint exposed by the spring boot gRPC server.
// See https://aka.ms/new-console-template for more information using com.javainuse.employee; using Grpc.Net.Client; Console.WriteLine("Hello, World!"); var channel = GrpcChannel.ForAddress("http://localhost:8090"); var client = new BookService.BookServiceClient(channel); bookRequest bookRequest = new bookRequest(); bookRequest.BookId = "1"; var reply = await client.getBookAsync(bookRequest); Console.WriteLine(reply.ToString());Run the console application. We can see that it consumes the exposed gRPC endpoint.
Download Source Code
Download it - C# + gRPC Client ExampleDownload it - Spring Boot + gRPC Server Example