2020年6月14日 星期日

[ASP.NET Core] gRPC - Get started


 ASP.NET Core   gRPC   protobuf  



(Picture from grpc.io)





Introduction


Before get started with develop gRPC service, you might want to see Introduction to gRPC.



Term
Description
Protobuf (Protocal Buffers)
Define the message structure in fields(name-value pairs). The protocol buffer compiler (protoc) will generate data access models and interfaces in our preferred language.
Channels
A gRPC channel provides a connection to a gRPC server on a specified host and port.


There are four kinds of service method:

Service method
Description
Unary RPCs
The client sends a single request to the server and gets a single response back
Server streaming RPCs
The client sends a request to the server and gets a stream to read a sequence of messages back. The respond message will be guaranteed in order from the server.
Client streaming RPCs
The client writes a sequence of messages and sends them to the server within a provided stream. The server returns a response after reading all of the incoming messages from the client.
Bidirectional streaming RPCs
Both the server and client send a sequence of messages using a read-write stream. The two streams operate independently but each of them preserves the order of messages.


Here is an example of using the four kinds of gRPC service methods in Key Management System (KMS).


1.  Unary RPCs: the client requests for a session key, and server responds one for it.





2.  Server streaming RPCs: the client requests for multiple keys, and server writes the keys to the Response Stream while the client can get each of the keys asynchronously by reading the Response stream.





3.  Client streaming RPCs: the client send its own keys to server by writing each of them to the Request Stream, and the server audit each of the keys to see if it is legal. After the server receives(reads) all the keys from the Request Stream, it returns the audit result.







4.  Bidirectional streaming RPCs: the client sends(writes) each of the expired keys to the Request Stream, and server returns(writes) each of the new keys to the Response Stream.





Notice that the Request and Response Streams operate independently, so the server can responds immediately after receiving a request, or responds after receiving more requests like following,









Related articles

1. N/A







Environment


dotnet core SDK 3.1.301
Protocol Buffers: proto3



Implement


Requirement

Dotnet core SDK > 3.0 is required, download it here.


gRPC service (Server side)

Create a new gRPC service project by Visual Studio 2019 (or above),



 

Or create one by dotnet CLI,

$ dotnet new grpc --name MyGrpc


Notice that we have the package:

There will be one protobuf file: greet.proto, with the following properties




The properties are kept in the .csproj,

 <ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
  </ItemGroup>


The protobuf’s definition:

syntax = "proto3";

option csharp_namespace = "Kms.gRPC";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequestreturns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}



csharp_namespace:

This option will make the Protocol Buffer compiler to generate the classes with the default namespace as the value of csharp_namespace.


service:

The service definition with one or more methods. We will have a static partial class named “Greeter” after compiled.


message:

The definition(model) of a request or response.



When the project is built, the related model and service classes will be created in obj/Debug/netcoreapp3.1/





Implement gRPC service


Create a class and inherits Greeter.GreeterBase, which is generated by the Protocol Buffer compiler, and override the defined method(s).

public class GreetService : Greeter.GreeterBase
{
        public override async Task<HelloReplySayHello(HelloRequest requestServerCallContext context)
        {
            return await Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
}


Now we have the gRPC service, its time to implement the client side.


Create new console project as gRPC client (Client side)

$ dotnet new console --name MyGrpc.Client



Install packages

Package name
Description
Note
C# runtime library for Protocol Buffers - Google's data interchange format.

.NET client for gRPC

HttpClientFactory integration the for gRPC .NET client
Optional. We can add the IHttpClientFactory to IServiceProvider.
gRPC and Protocol Buffer compiler for managed C# and native C++ projects.




Then copy the protobuf file(s), e.q. greet.proto, from server-side project to client-side project with the following properties.





The properties are kept in the .csproj,

<ItemGroup>
    <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
  </ItemGroup>


Which will be built into  obj/Debug/netcoreapp3.1/




Calling service methods

Here is an example to create a new OU by LDAP tool: LdapAdmin.
We can simply use Greeter.GreeterClient, which is generated by Protocol Buffer compiler, to call the gRPC service method(s).

For example,

using var channel = GrpcChannel.ForAddress("https://localhost:5001");
var client = new Greeter.GreeterClient(channel);
var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });

Console.WriteLine(reply.Message);
// shows: "Hello GreeterClient"



We will see more details about how to implement the four kinds of service method in next article.




Reference








沒有留言:

張貼留言