Section 2 of 6

gRPC

🎯 What You'll Learn

  • What is gRPC
  • Protocol Buffers
  • Creating gRPC service
  • gRPC client
  • Streaming

What is gRPC?

gRPC is a high-performance RPC framework using HTTP/2 and Protocol Buffers for efficient communication between services.

gRPC vs REST

Aspect gRPC REST
Protocol HTTP/2 HTTP/1.1
Format Protocol Buffers (binary) JSON (text)
Performance Faster Slower
Streaming Built-in Not supported
Browser Support Limited Full

Create gRPC Service

Create Project Bash
dotnet new grpc -n ProductService

Protocol Buffers (.proto)

Protos/product.proto Protobuf
syntax = "proto3";

option csharp_namespace = "ProductService";

service ProductService {
  rpc GetProduct (ProductRequest) returns (ProductReply);
  rpc ListProducts (Empty) returns (stream ProductReply);
}

message ProductRequest {
  int32 id = 1;
}

message ProductReply {
  int32 id = 1;
  string name = 2;
  double price = 3;
}

message Empty {}

Implement Service

Services/ProductService.cs C#
public class ProductService : ProductService.ProductServiceBase
{
    private readonly InvenTrackDbContext _context;

    public override async Task<ProductReply> GetProduct(
        ProductRequest request, 
        ServerCallContext context)
    {
        var product = await _context.Products.FindAsync(request.Id);
        
        return new ProductReply
        {
            Id = product.Id,
            Name = product.Name,
            Price = (double)product.Price
        };
    }

    public override async Task ListProducts(
        Empty request, 
        IServerStreamWriter<ProductReply> responseStream, 
        ServerCallContext context)
    {
        var products = await _context.Products.ToListAsync();
        
        foreach (var product in products)
        {
            await responseStream.WriteAsync(new ProductReply
            {
                Id = product.Id,
                Name = product.Name,
                Price = (double)product.Price
            });
        }
    }
}

Register Service

Program.cs C#
builder.Services.AddGrpc();

var app = builder.Build();

app.MapGrpcService<ProductService>();

gRPC Client

Install Package Bash
dotnet add package Grpc.Net.Client
dotnet add package Google.Protobuf
dotnet add package Grpc.Tools
Client Code C#
using Grpc.Net.Client;

var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new ProductService.ProductServiceClient(channel);

// Call service
var reply = await client.GetProductAsync(new ProductRequest { Id = 1 });
Console.WriteLine($"Product: {reply.Name}, Price: {reply.Price}");

Key Takeaways

  • gRPC: High-performance RPC framework
  • Protocol Buffers: Binary serialization format
  • .proto files: Define service contracts
  • HTTP/2: Faster than REST
  • Streaming: Server/client/bidirectional streaming
  • Best for: Microservices communication