C#でgRPCを使ってみた

はじめに

C#でgRPCを使い、簡単なサンプルを作って動かしてみました。

プロジェクト

以下の3つのプロジェクトを作成しました。
・GrpcExample
・GrpcExampleClient
・GrpcExampleServer

GrpcExample

Nugetの追加

Nugetで以下を3つをインストールします。
・Google.Protobuf
・Grpc.Net.Client
・Grpc.Tools

サービスの定義

サービス定義用のファイルを追加します。
「grpc_example.proto」というファイルを追加し、ビルドアクションを「Protobuf compiler」にします。

.protoファイルの中身は以下のようにしました。
Sayというメソッドがあり、引数がGrpcExampleRequest、戻り値がGrpcExampleResponseという定義をしています。

syntax = "proto3";
 
option csharp_namespace = "GrpcExampleProto";
 
service GrpcExample {
  rpc Say (GrpcExampleRequest) returns (GrpcExampleResponse) {}
}
 
message GrpcExampleRequest {
  string name = 1;
  string addMessage = 2;
}
 
message GrpcExampleResponse {
  string message = 1;
  string messageCount = 2;
}

このプロジェクトをビルドすると、「GrpcExample.cs」や「GrpcExampleGrpc.cs」が作成されるので、
後述のgRPCクライアントやgRPCサーバから呼び出します。

GrpcExampleServer

gRPCサーバです。
単純な文字列作成して返すだけです。

using Grpc.Core;
using GrpcExampleProto;
using System;
using System.Threading.Tasks;
 
namespace GrpcExampleServer
{
    class GrpcExampleImpl : GrpcExample.GrpcExampleBase
    {
        public override Task Say(GrpcExampleRequest request, ServerCallContext context)
        {
            return Task.FromResult(new GrpcExampleResponse { Message = $"こんにちは、{request.Name}さん。" + request.AddMessage });
        }
    }
    class Program
    {
        const int Port = 30051;
        static void Main(string[] args)
        {
            Server server = new Server
            {
                Services = { GrpcExample.BindService(new GrpcExampleImpl()) },
                Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
            };
            server.Start();
            Console.ReadKey();
            server.ShutdownAsync().Wait();
        }
    }
}

GrpcExampleClient

gRPCクライアントです。
GrpcExampleServerの処理を呼び出しています。

using Grpc.Core;
using GrpcExampleProto;
using System;
 
namespace GrpcExampleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Channel channel = new Channel("localhost:30051", ChannelCredentials.Insecure);
 
            var client = new GrpcExample.GrpcExampleClient(channel);
            var name = "太郎";
            var addMessage = "よろしくお願いします。";
 
            var reply = client.Say(new GrpcExampleRequest { Name = name, AddMessage = addMessage });
            Console.WriteLine(reply.Message);
 
            channel.ShutdownAsync().Wait();
            Console.ReadKey();
        }
    }
}

実行結果

「こんにちは、太郎さん。よろしくお願い致します。」という文字列が返ってきます。

未分類C#

Posted by ababa