Grpc 实现 终极(三) 重新 提取公共项目
由于 annotations.proto http.proto 两个文件 服务端 和 客户端都需要 我这里 尝试 提取到公共项目中去
看看会遇到哪些问题 下面是公共项目

公共项目 引用
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> </PropertyGroup> <ItemGroup> <PackageReference Include="Grpc.AspNetCore" Version="2.70.0" /> </ItemGroup> </Project>
类库项目 应用 公共项目 其实这样不好 因为 实际项目 有 仓储 所以 这样 达不到灵活

syntax = "proto3"; option csharp_namespace = "StudentGrpc"; package studentgrpcwebapi; import "google/api/annotations.proto"; ///学生服务grpc service StudentService { //获取学生 rpc GetStudent (DataRequest) returns (DataResponse) { option (google.api.http) = { get: "/v1/WebApi/{name}" }; } } //学生服务 message DataRequest { string name = 1; } message DataResponse { repeated Student students =1; } message Student{ string Id =1; string name =2; }
实现类
using Google.Protobuf; using Grpc.Core; using StudentGrpc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGrpc { /// <summary> /// 学生 grpc service /// </summary> public class StudentServiceImp : StudentGrpc.StudentService.StudentServiceBase { private static List<StudentGrpc.Student> students = new List<StudentGrpc.Student>() { new StudentGrpc.Student { Id = "001", Name = "小明" }, new StudentGrpc.Student { Id = "002", Name = "小李" } }; /// <summary> /// 获取 学生 by name /// </summary> /// <param name="request"></param> /// <param name="context"></param> /// <returns></returns> public override Task<DataResponse> GetStudent(DataRequest request, ServerCallContext context) { List<StudentGrpc.Student> list = students.Where(item => item.Name.Contains(request.Name)).ToList(); var data = new DataResponse(); data.Students.AddRange(list); return Task.FromResult(data); } } }
下面标红 必须引用 否则报错
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateDocumentationFile>True</GenerateDocumentationFile> </PropertyGroup> <ItemGroup> <None Remove="StudentGrpcServer.proto" /> </ItemGroup> <ItemGroup> <PackageReference Include="Grpc.AspNetCore" Version="2.70.0" /> <PackageReference Include="Google.Api.CommonProtos" Version="2.16.0" /> <PackageReference Include="Google.Protobuf" Version="3.30.2" /> <PackageReference Include="Microsoft.AspNetCore.Grpc.JsonTranscoding" Version="8.0.3" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\..\GrpcCore\GrpcCore\GrpcCore.csproj" /> </ItemGroup> <ItemGroup> <Protobuf Include="StudentGrpcServer.proto"> <AdditionalImportDirs>../../GrpcCore/GrpcCore</AdditionalImportDirs> </Protobuf> </ItemGroup> </Project>
webapi 服务项目
UseHttps(); 隐式开启了 http2
using StudentGrpc; using System.Reflection; using TestGrpc; namespace TestWebAPiGrpc { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(p => { string basePath = AppDomain.CurrentDomain.BaseDirectory; string xmlFileName = Assembly.GetEntryAssembly().GetName().Name + ".xml"; string xmlPath = Path.Combine(basePath, xmlFileName); string grpcXmlPath = Path.Combine(basePath, "TestGrpc.xml"); p.IncludeXmlComments(xmlPath, true); p.IncludeGrpcXmlComments(grpcXmlPath, true); p.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "grpc Test", Description = "grpc Test", Version = "v1", }); }).AddGrpcSwagger(); // builder.Services.AddSwaggerGen().AddGrpcSwagger(); builder.Services.AddGrpc(); builder.WebHost.ConfigureKestrel(p => { //http p.ListenAnyIP(5134); //http p.ListenAnyIP(5135); //https p.ListenAnyIP(7069, k => { k.UseHttps(); }); }); var app = builder.Build(); app.MapGrpcService<StudentServiceImp>(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(p => { p.SwaggerEndpoint("/swagger/v1/swagger.json", "v1"); }); } // app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); } } }
webapi引用
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <GenerateDocumentationFile>True</GenerateDocumentationFile> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Grpc.Swagger" Version="0.8.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestGrpc\TestGrpc.csproj" /> </ItemGroup> </Project>
客户端
using Grpc.Net.Client; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using StudentGrpc; namespace TestGrpcClient.Controllers { [Route("api/[controller]")] [ApiController] public class TestGrpcsController : ControllerBase { [HttpGet] public IActionResult Get([FromQuery] string query) { GrpcChannel grpcChannel = GrpcChannel.ForAddress(new Uri("https://localhost:7069")); StudentGrpc.StudentService.StudentServiceClient client = new StudentGrpc.StudentService.StudentServiceClient(grpcChannel); DataRequest request = new DataRequest { Name = query }; var student = client.GetStudent(request)?.Students; return Ok(student); } } }
客户端引用
这句重点 是 引用公共项目 中的两个文件
<AdditionalImportDirs>../../GrpcCore/GrpcCore</AdditionalImportDirs>
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <None Remove="StudentGrpcServer.proto" /> </ItemGroup> <ItemGroup> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\TestGrpc\TestGrpc.csproj" /> </ItemGroup> <ItemGroup> <Protobuf Include="StudentGrpcServer.proto" GrpcServices="Client"> <AdditionalImportDirs>../../GrpcCore/GrpcCore</AdditionalImportDirs> </Protobuf> </ItemGroup> </Project>
测试服务端


测试客户端

成功

浙公网安备 33010602011771号