Grpc客户端Proto文件独立库,供多个客户端项目引用

1、新建netcore控制台应用程序

 

 

 

 2、NuGet包下载安装

Grpc.Net.Client
Google.ProtoBuf
Grpc.Tools

3、新建Protos文件夹,将服务端的greet.proto复制到该文件夹下

syntax = "proto3";

option csharp_namespace = "MyGrpcWeb";

package MyGrpc;

// The greeting service definition.
service TestGrpc {
  // Sends a greeting
  rpc TestSay (TestRequest) returns (TestReply);

  rpc StreamingFromServer(ExampleRequest) returns (stream ExampleResponse);

  rpc StreamingFromClient(stream ExampleRequest) returns (ExampleResponse);

  rpc StreamingBothWays(stream ExampleRequest) returns (stream ExampleResponse);
}

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

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

message ExampleRequest{
int32 pageIndex=1;
int32 pageSize=2;
bool isDescending=3;
}

message ExampleResponse{
string name=1;
string sex=2;
}

4、设置属性

 

 

 

5、重新生成解决方案

6、客户端引用

 

 

 7、新建GrpcServer.cs

using Grpc.Net.Client;
using MyGrpcWeb;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.GrpcService
{
    public class GrpcServer
    {
        private readonly TestGrpc.TestGrpcClient _testGrpcClient;
        private readonly GrpcChannel _channel;

        public TestGrpc.TestGrpcClient MyGrpcClient
        {
            get { return _testGrpcClient; }
        }
        public GrpcServer()
        {
            _channel = GrpcChannel.ForAddress("http://localhost:5000");
            _testGrpcClient = new TestGrpc.TestGrpcClient(_channel);
        }

    }
}

 

posted @ 2021-08-28 20:07  天众师兄  阅读(275)  评论(0编辑  收藏  举报