In this article, we will learn about the basics of gRPC and its usage and, finally, implement the Server and Client using .NET Core 8.0.
gRPC explained:
gRPC (Google Remote Procedure Calls) was initially created by Google, which has used a single general-purpose RPC infrastructure called Stubby to connect the large number of microservices running within and across its data centers for over a decade.
In March 2015, Google decided to build the next version of Stubby and make it open source and the result was gRPC.
- gRPC is a modern open-source high-performance Remote Procedure Call (RPC) framework.
- It implements APIs using HTTP/2 which can run in any environment.
- gRPC has two parts
- gRPC Protocol - As mentioned above it uses HTTP/2 which provides a lot of advantages over traditional HTTP1.x
- Data Serialization - by default gRPC uses Protobuf for the serialization and as an intermediator between client and server.
- gRPC clients and servers intercommunicate using a variety of environments and machines.
- It supports many languages like Java, C#, Go, Ruby, and Python, check the full list here.
- It supports pluggable auth, tracing, load balancing, and health checking.
Different scenarios in which we use gRPC
- When we use microservice architecture, and we use that for internal communication from one or more servers.
- gRPC is handy when performance is on high priority with low latency.
- It is useful when we require duplex communication between services with different types of data.
- gRPC is useful in the last mile of distributed computing to connect devices, mobile applications, and browsers to backend services.
gRPC vs REST:
REST has been one of the highly used API frameworks and with gRPC grabbing the limelight, let's see the comparison on various parameters.
REST | gRPC | |
---|---|---|
Protocol | HTTP/1.1 | HTTP/2.0 |
Request-Response Model | Only supports Request Response as based on HTTP/1.1 | Supports All Types Of Streaming as based on HTTP/2 |
Serialization | JSON/XML | protobuf |
Payload Format | Serialization like JSON/XML | Strong Typing |
Browser Support | Yes | No |
Pros and Cons of gRPC:
Pros
- With duplex communication, it supports bi-directional streaming with HTTP/2-based transport.
- Performance is one of the talking points of gRPC and it is faster than REST and SOAP.
- gRPC services are highly efficient on wire and with a simple service definition framework.
- gRPC messages are lightweight compared to other types such as JSON.
- Client libraries supporting the 11 languages.
Cons
- Browser support is very limited.
- Since it uses binary data which is not easily readable compared to JSON or XML.
gRPC Implementation
Prerequisites
- Visual Studio 2022
- .NET 8.0
Set Up gRPC Service:
- Open Visual Studio 2022 and create a new gRPC project with the name GrpcCoreService and select
.NET 8.0
under the Framework option. -
Review the default project folder structure.
-
Protos: contains all the gRPC server asset files, such as
greet.proto
- Services: Contains the implementation of the gRPC services.
-
Root Folder:
appSettings.json
contains the service configuration andProgram.cs
contains code configuring app behavior.
-
Protos: contains all the gRPC server asset files, such as
Right-click on the
greet.proto
and click on Properties, and verify that gRPC Stub Classes is set to Server only.
Set Up Client Application:
- Add a Console App Project with the name GrpcClientApp and select the required configurations.
- Add the required packages to the client app project.
Install-Package Grpc.Net.Client
Install-Package Google.Protobuf
Install-Package Grpc.Tools
- Create a Protos folder and copy the
Protos\greet.proto
file from the GrpcCoreService under this folder. - Update the namespace inside the
greet.proto
file to the project's namespace:
option csharp_namespace = "GrpcClientApp";
After that right-click on
greet.proto
and click on Properties, and set the gRPC Stub Classes to Client only.
Finally, edit the GrpcClientApp.csproj project file:
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>
- Once this is completed update the
Program.cs
file to call the greeter service.
using Grpc.Net.Client; | |
using GrpcClientApp; | |
var message = new HelloRequest | |
{ | |
Name = "Sandeep Kumar" | |
}; | |
var channel = GrpcChannel.ForAddress("http://localhost:5181"); | |
var client = new Greeter.GreeterClient(channel); | |
var serverResponse = await client.SayHelloAsync(message); | |
Console.WriteLine(serverResponse.Message); | |
Console.WriteLine("Press any key to exit..."); | |
Console.ReadKey(); |
Make sure to use the port number mentioned in the
launchSettings.json
files of the GrpcCoreService project.
Run and Test:
-
Set Up StartUp Project: Configure both projects as startup projects in the proper order.
- Run the project and review the output of both the gRPC service and the client in the Console window.
- gRPC Service Window:
- gRPC Client Window:
Setup new service and client:
So far we have tested the default greeter service and client.
Now let's move ahead and set up a new service and client that consumes this new service.
Setup employee service:
- To start with add the
employee.proto
file under theProtos
folder and add the following code.
syntax = "proto3"; | |
option csharp_namespace = "GrpcCoreService.EmployeeProtos"; | |
package employee; | |
service Employee { | |
rpc GetEmpInformation (GetEmpDetail) returns (EmpModel); | |
} | |
message GetEmpDetail{ | |
int32 empId = 1; | |
} | |
message EmpModel{ | |
string empName = 1; | |
string empEmail = 2; | |
string empRole = 3; | |
string empDepartment = 4; | |
} |
- Under the
Services
folder add theEmployeeService.cs
and implement it as shown below.
using Grpc.Core; | |
using GrpcCoreService.EmployeeProtos; | |
namespace GrpcCoreService.Services | |
{ | |
public class EmployeeService : Employee.EmployeeBase | |
{ | |
private readonly ILogger<EmployeeService> _logger; | |
public EmployeeService(ILogger<EmployeeService> logger) | |
{ | |
_logger = logger; | |
} | |
public override Task<EmpModel> GetEmpInformation(GetEmpDetail request, ServerCallContext context) | |
{ | |
var employee = new EmpModel(); | |
switch (request.EmpId) | |
{ | |
case 1: | |
return Task.FromResult(new EmpModel | |
{ | |
EmpName = "Sandeep Kumar", | |
EmpEmail = "sk@testorg.com", | |
EmpDepartment = "Information Technology", | |
EmpRole = "Technical Leader" | |
}); | |
case 2: | |
return Task.FromResult(new EmpModel | |
{ | |
EmpName = "Test Emp2", | |
EmpEmail = "testemp2@testorg.com", | |
EmpDepartment = "Finance", | |
EmpRole = "Manager" | |
}); | |
case 3: | |
return Task.FromResult(new EmpModel | |
{ | |
EmpName = "Test Emp3", | |
EmpEmail = "testemp3@testorg.com", | |
EmpDepartment = "HR", | |
EmpRole = "Associate" | |
}); | |
case 4: | |
return Task.FromResult(new EmpModel | |
{ | |
EmpName = "Test Emp4", | |
EmpEmail = "testemp4@testorg.com", | |
EmpDepartment = "Operation", | |
EmpRole = "Analyst" | |
}); | |
case 5: | |
return Task.FromResult(new EmpModel | |
{ | |
EmpName = "Test Emp5", | |
EmpEmail = "testemp5@testorg.com", | |
EmpDepartment = "Executive", | |
EmpRole = "Director" | |
}); | |
default: | |
return Task.FromResult(employee); | |
} | |
} | |
} | |
} |
- Inject this new service under the
Program.cs
.
app.MapGrpcService<EmployeeService>();
Update the client app to consume the employee service:
- Copy the
employee.proto
file from the GrpcCoreService and update the namespace:
option csharp_namespace = "GrpcClientApp";
- After that right-click on the
employee.proto
and click on Properties and set the gRPC Stub Classes to Client only - And make sure the proto file is added in the GrpcClientApp.csproj project file:
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
<Protobuf Include="Protos\employee.proto" GrpcServices="Client" />
</ItemGroup>
- Finally, update the
Program.cs
file to call theemployee
service.
using Grpc.Net.Client; | |
using GrpcClientApp; | |
var channel = GrpcChannel.ForAddress("http://localhost:5181"); | |
var client = new Employee.EmployeeClient(channel); | |
Console.WriteLine("Enter Employee ID...."); | |
var inputStr = Console.ReadLine(); | |
int empId = 0; | |
if (!int.TryParse(inputStr, out empId)) | |
{ | |
Console.WriteLine("This is invalid Employee ID, please exit and try again...."); | |
} | |
else | |
{ | |
var emp = new GetEmpDetail { EmpId = empId }; | |
var serverResponse = await client.GetEmpInformationAsync(emp); | |
Console.WriteLine("Employee Name | Role | Email ID | Department"); | |
Console.WriteLine($"{serverResponse.EmpName} | {serverResponse.EmpRole} | {serverResponse.EmpEmail} | {serverResponse.EmpDepartment}"); | |
} | |
Console.WriteLine("Press any key to exit..."); | |
Console.ReadKey(); |
- Once you are done with changes, you can verify the folders and files under Solution Explorer.
Run and Test the new service:
- Run the project and search for the employee by passing the Employee ID in the Console Window
NOTE:
Check the source code here.
sandeepkumar17
/
GrpcCoreService
.NET 8.0 - gRPC implementation
.NET8.0 - gRPC Service and Client implementation
Introduction
- gRPC (Google Remote Procedure Calls) is a modern open-source high-performance Remote Procedure Call (RPC) framework that can run in any environment.
- It can efficiently connect services in and across data centers with pluggable support for load balancing, tracing, health checking, and authentication.
- It is also applicable in the last mile of distributed computing to connect devices, mobile applications, and browsers to backend services.
Solution and Project setup:
Set Up gRPC Service:
-
Open Visual Studio 2022 and create a new gRPC project, and name it to GrpcCoreService and select .NET 8.0 under the Framework option.
-
Right-click on greet.proto and click on Properties and verify that gRPC Stub Classes is set to Server only.
Set Up Client Application:
If you have any comments or suggestions, please leave them behind in the comments section below.
Top comments (0)