vs2019 .net core 3.1 使用GRPC 多個proto文件


服務端:

1.使用vs2019創建GRPC服務端

2.在項目下的Protos文件夾創建.proto文件

 

內容設置如下:

syntax = "proto3";

// 命名空間
option csharp_namespace = "GrpcService1";
package first;

//定義的服務
service ProFirst { 
  // 方法
  rpc SayHello (LxpRequest) returns (LxpReply); 
  // 方法
  rpc GetUserInfo(LxpRequest) returns(LxpReply); 
}
 //請求體
message LxpRequest { 
  string name = 1;
  string  age = 4;
}
 //響應體
message LxpReply { 
  string message = 1;

}

 

3.右鍵項目->編輯項目文件->將創建的.proto文件添加進去,vs2019自動生成代碼

 

 

 

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<!--此處為proto文件的路徑,編輯器會去查找對應的proto文件並生成代碼-->
<!--注意此處的 GrpcServices 屬性需要設置為Server,如果是客戶端的話需要設置為Client-->
<Protobuf Include="Protos\greet.proto" GrpcServices="Server" />
<Protobuf Include="Protos\first.proto" GrpcServices="Server" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.27.0" />
</ItemGroup>

</Project>

 

設置完成會在項目的obj>debug>netcoreapp3.1目錄下自動生成對應的代碼

 

 

 

3.在項目下的Services文件

 

 在Service文件夾添加類,讓該類繼承proto自動生成的代碼,並且重寫,這里需要注意的是 每次在proto文件新增方法的時候需要在該文件實現,否則會調用錯誤,報未實現的錯誤

using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Threading.Tasks;

namespace GrpcService1
{
    // 這里繼承proto文件生成的服務抽象類,需要自己實現
    public class FirstService : ProFirst.ProFirstBase
    {
        private readonly ILogger<FirstService> _logger;
        public FirstService(ILogger<FirstService> logger)
        {
            _logger = logger;
        }

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override Task<LxpReply> GetUserInfo(LxpRequest request, ServerCallContext context)
        {
            return Task.FromResult(new LxpReply { Message = "LXP  我愛你" });

        }

        public override Task<LxpReply> SayHello(LxpRequest request, ServerCallContext context)
        {
            return Task.FromResult(new LxpReply { Message = "LXP 你好" });
        }

        public override string ToString()
        {
            return base.ToString();
        }
    }
}

 

4.在startup類文件配置grpc

startup文件中需要啟用,在ConfigureServices注冊服務,Configure設置服務的終結點

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace GrpcService1
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGrpcService<FirstService>();//自己新加的服務類
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }
    }
}

 

5.在appsettings.json文件配置http2

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "EndpointDefaults": {
      "Protocols": "Http2"
    }
  }
}

 然后在測試的時候需要使用臨時的證書,點擊確定,如果需要發布到正式環境下需要申請證書

點擊運行

 

 

 客戶端(控制台或asp.net mvc等等):

1.安裝nuget包 grpc-aspnetcore 

 

 

2.將服務端的Protos文件夾整個復制到客戶端

 

 

3.右鍵項目->編輯項目文件->將創建的.proto文件添加進去,將Server修改為Client,vs2019自動生成代碼

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp3.1</TargetFramework>
    </PropertyGroup>

    <ItemGroup>
        <None Remove="Protos\first.proto" />
    </ItemGroup>

    <ItemGroup>
        <PackageReference Include="Grpc.AspNetCore" Version="2.27.0" />
    </ItemGroup>
    <ItemGroup>
        <!--這里需要注意GrpcServices修改為Client-->
        <Protobuf Include="Protos\first.proto" GrpcServices="Client" />
        <Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
    </ItemGroup>
</Project>

 

4.開始愉快的使用,在項目需要的地方調用

using Grpc.Core;
using Grpc.Net.Client;
using GrpcService1;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var client = new Greeter.GreeterClient(channel);

            var sayHello = client.SayHello(new HelloRequest { Name = "123" });
            var sayHelloAsync = await client.SayHelloAsync(new HelloRequest { Name = "123" });

            var client1 = new ProFirst.ProFirstClient(channel);
            var client1SayHello = client1.SayHello(new LxpRequest { Name = "123", Age = "123" });
            var userInfo = client1.GetUserInfo(new LxpRequest { Name = "321", Age = "abc" });
            var userInfoAsync = await client1.GetUserInfoAsync(new LxpRequest { Name = "321", Age = "abc" });
            Console.WriteLine("Hello World!");
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM