ShowProgramCode

2022年8月5日 星期五

C# 連結Golang的Grpc Server

Grpc Client專案要如何設定,請參考之前的文章
這裡主要說明的是如何使用C# .NetCore作為Client連結Golang的Grpc Server。

Golang Grpc Server proto調整

syntax = "proto3";  // 定義要使用的 protocol buffer 版本

option csharp_namespace = "GrpcTestApi";

package grpcServer;  // for name space
//option go_package = "./;grpcServer";  // generated code 的 full Go import path

message SumRequest {
  repeated int64 input = 1 [packed=true];
}

message SumResponse {
  int64 result = 1;
}

message RemainderRequest{
  int64 a = 1;
  int64 b = 2;
}

message RemainderResponse {
  int64 result = 1;
}

service grpcService {
  rpc Sum(SumRequest) returns (SumResponse) {};
  rpc Remainder(RemainderRequest) returns (RemainderResponse) {};
}

連線Grpc Client Help物件

public class GrpcServerConnectHelp
{
    private string serverUrl;
    private grpcService.grpcServiceClient client;

    public string ServerUrl { get { return serverUrl; } }

    public GrpcServerConnectHelp()
    {
        Init(System.Configuration.ConfigurationManager.AppSettings.Get("GrpcServerUrl"));
    }

    public void Init(string url = null)
    {
        if (string.IsNullOrEmpty(url))
            return;

        serverUrl = url;
        //.NetCore 3.*版本必須加入此行,否則會錯誤。
        AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
        var channel = GrpcChannel.ForAddress(serverUrl);
        client = new grpcService.grpcServiceClient(channel);
    }

    public string CommonApi(string method, string input)
    {
        string resp = "查無此函式";

        if (method.Equals("Sum"))
        {
            return Sum(input);
        }

        if(method.Equals("Remainder"))
        {
            return Remainder(input);
        }

        return resp;
    }

    private string Sum(string input)
    {
        dynamic dyn = JsonConvert.DeserializeObject(input);
        SumRequest request = new SumRequest();

        foreach(var value in dyn.Input)
        {
            long temp = Convert.ToInt64(value);
            request.Input.Add(temp);
        }
        var reply = client.Sum(request);
        return reply.Result.ToString();
    }

    private string Remainder(string input)
    {
        dynamic dyn = JsonConvert.DeserializeObject(input);
        RemainderRequest request = new RemainderRequest();
        request.A = dyn.A;
        request.B = dyn.B;

        var reply = client.Remainder(request);
        return reply.Result.ToString();
    }
}

AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

重點在於.Net Core 3.*的版本再傳入URL前,必須加入上面的語法,否則會產生錯誤

沒有留言:

張貼留言