集成gRPC模块

This commit is contained in:
YUN-PC5\user 2023-10-13 16:56:33 +08:00
parent 28c53b71ce
commit 52cd22c4c6
11 changed files with 217 additions and 3 deletions

View File

@ -0,0 +1,59 @@
using System;
namespace ZR.Infrastructure.Resolver;
public static class AntPathMatcher
{
public static bool Match(string pattern, string value)
{
if (pattern == null || value == null)
return false;
if (pattern == "**")
return true;
var patternSegments = pattern.Split('/');
var valueSegments = value.Split('/');
int patternIndex = 0;
int valueIndex = 0;
int patternWildcardIndex = -1;
int valueWildcardIndex = -1;
while (valueIndex < valueSegments.Length)
{
if (patternIndex < patternSegments.Length && IsMatch(patternSegments[patternIndex], valueSegments[valueIndex]))
{
patternIndex++;
valueIndex++;
}
else if (patternWildcardIndex != -1)
{
patternIndex = patternWildcardIndex + 1;
valueIndex = ++valueWildcardIndex;
}
else
{
return false;
}
}
while (patternIndex < patternSegments.Length && patternSegments[patternIndex] == "**")
{
patternIndex++;
}
return patternIndex >= patternSegments.Length && valueIndex >= valueSegments.Length;
}
private static bool IsMatch(string patternSegment, string valueSegment)
{
if (patternSegment == "*")
return true;
if (patternSegment.StartsWith("{") && patternSegment.EndsWith("}"))
return true; // 支持占位符的匹配逻辑
return string.Equals(patternSegment, valueSegment, StringComparison.OrdinalIgnoreCase);
}
}

View File

@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace ZR.Infrastructure.Resolver;
public class PropertyFilterContractResolver : CamelCasePropertyNamesContractResolver
{
private readonly HashSet<string> _includedPaths;
private readonly HashSet<string> _excludedPaths;
public PropertyFilterContractResolver(IEnumerable<string> includedPaths, IEnumerable<string> excludedPaths)
{
_includedPaths = includedPaths.ToHashSet();
_excludedPaths = excludedPaths.ToHashSet();
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var properties = base.CreateProperties(type, memberSerialization);
properties = properties.Where(p => IsIncluded(p) && !IsExcluded(p)).ToList();
return properties;
}
private bool IsIncluded(JsonProperty property)
{
if (_includedPaths == null || _includedPaths.Count == 0)
return true;
return _includedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
}
private bool IsExcluded(JsonProperty property)
{
if (_excludedPaths == null || _excludedPaths.Count == 0)
return false;
return _excludedPaths.Any(path => AntPathMatcher.Match(path, property.PropertyName));
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace ZR.Admin.Grpc.Extensions;
public static class GrpcServiceExtensions
{
public static void AddGrpcServiceConfiguration(this IServiceCollection services, IConfiguration configuration)
{
// services.AddTransient<AuthUn>()
services.AddGrpcClient<Greeter.GreeterClient>(options =>
{
options.Address = new Uri(configuration.GetValue<string>("GrpcUrls:FindTeacher"));
});
}
}

View File

@ -0,0 +1,17 @@
syntax = "proto3";
option csharp_namespace = "GrpcService1";
package block;
service Block {
rpc GetBlock (BlockRequest) returns (BlockReply);
}
message BlockRequest {
string in = 1;
}
message BlockReply {
string out = 1;
}

View File

@ -0,0 +1,21 @@
syntax = "proto3";
option csharp_namespace = "ZR.Admin.Grpc";
package greet;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply);
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings.
message HelloReply {
string message = 1;
}

View File

@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client"/>
<Protobuf Include="Protos\block.proto" GrpcServices="Client"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.49.0"/>
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
</Project>

View File

@ -4,7 +4,8 @@
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true" autoReload="true"
internalLogLevel="Info" internalLogLevel="Info"
internalLogFile="nlog-internal.log"> internalLogFile="nlog-internal.log"
throwConfigExceptions="true">
<!--Nlog 文档参考地址https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-2--> <!--Nlog 文档参考地址https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-2-->
<!--internalLogLevel Nlog内部日志记录为Off关闭。除非纠错不可以设为Trace否则速度很慢起码Debug以上--> <!--internalLogLevel Nlog内部日志记录为Off关闭。除非纠错不可以设为Trace否则速度很慢起码Debug以上-->

View File

@ -4,12 +4,20 @@ using Microsoft.AspNetCore.DataProtection;
using NLog.Web; using NLog.Web;
using System.Text.Json; using System.Text.Json;
using BloomFilter.CSRedis.Configurations; using BloomFilter.CSRedis.Configurations;
using Grpc.Net.Client;
using GrpcService1;
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis; using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ZR.Admin.Grpc;
using ZR.Admin.Grpc.Extensions;
using ZR.Admin.WebApi.Extensions; using ZR.Admin.WebApi.Extensions;
using ZR.Infrastructure.Cache; using ZR.Infrastructure.Cache;
using ZR.Infrastructure.Resolver;
using ZR.Infrastructure.WebExtensions; using ZR.Infrastructure.WebExtensions;
using ZR.ServiceCore.Model;
using ZR.ServiceCore.Services.IService; using ZR.ServiceCore.Services.IService;
using ZR.ServiceCore.Signalr; using ZR.ServiceCore.Signalr;
using ZR.ServiceCore.SqlSugar; using ZR.ServiceCore.SqlSugar;
@ -33,6 +41,8 @@ builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// 跨域配置 // 跨域配置
builder.Services.AddCors(builder.Configuration); builder.Services.AddCors(builder.Configuration);
// Grpc
builder.Services.AddGrpc();
// 显示logo // 显示logo
// builder.Services.AddLogo(); // builder.Services.AddLogo();
//消除Error unprotecting the session cookie警告 //消除Error unprotecting the session cookie警告
@ -100,7 +110,15 @@ builder.Services.AddSignalR()
options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
}); });
builder.Services.AddSwaggerConfig(); builder.Services.AddSwaggerConfig();
// using var channel = GrpcChannel.ForAddress("https://localhost:7025");
// var client = new Greeter.GreeterClient(channel);
// var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
// Console.WriteLine("Greeting: " + reply.Message);
//
// var blockClient = new Block.BlockClient(channel);
// var blockReply = await blockClient.GetBlockAsync(new BlockRequest { In = "asads" });
// Console.WriteLine("BlockReply: " + blockReply.Out);
builder.Services.AddGrpcServiceConfiguration(builder.Configuration);
var app = builder.Build(); var app = builder.Build();
InternalApp.ServiceProvider = app.Services; InternalApp.ServiceProvider = app.Services;
InternalApp.Configuration = builder.Configuration; InternalApp.Configuration = builder.Configuration;
@ -179,5 +197,13 @@ using (var serviceScope = app.Services.CreateScope())
var pol = await ipPolicyStore.GetAsync(optionsAccessor.Value.IpPolicyPrefix); var pol = await ipPolicyStore.GetAsync(optionsAccessor.Value.IpPolicyPrefix);
pol.IpRules.AddRange(ipRateLimitPolicies.Adapt<List<IpRateLimitPolicy>>()); pol.IpRules.AddRange(ipRateLimitPolicies.Adapt<List<IpRateLimitPolicy>>());
await ipPolicyStore.SetAsync(optionsAccessor.Value.IpPolicyPrefix, pol); await ipPolicyStore.SetAsync(optionsAccessor.Value.IpPolicyPrefix, pol);
var greeterClient = services.GetRequiredService<Greeter.GreeterClient>();
var helloReply = await greeterClient.SayHelloAsync(new HelloRequest
{
Name = "gree"
});
Console.WriteLine(helloReply);
} }
app.Run(); app.Run();

View File

@ -10,6 +10,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ZR.Admin.Grpc\ZR.Admin.Grpc.csproj" />
<ProjectReference Include="..\ZR.CodeGenerator\ZR.CodeGenerator.csproj" /> <ProjectReference Include="..\ZR.CodeGenerator\ZR.CodeGenerator.csproj" />
<ProjectReference Include="..\ZR.Service\ZR.Service.csproj" /> <ProjectReference Include="..\ZR.Service\ZR.Service.csproj" />
<ProjectReference Include="..\ZR.Tasks\ZR.Tasks.csproj" /> <ProjectReference Include="..\ZR.Tasks\ZR.Tasks.csproj" />

View File

@ -21,6 +21,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZR.CodeGenerator", "ZR.Code
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZR.ServiceCore", "ZR.ServiceCore\ZR.ServiceCore.csproj", "{4E2CC4E4-F109-4876-8498-912E13905765}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ZR.ServiceCore", "ZR.ServiceCore\ZR.ServiceCore.csproj", "{4E2CC4E4-F109-4876-8498-912E13905765}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ZR.Admin.Grpc", "ZR.Admin.Grpc\ZR.Admin.Grpc.csproj", "{41169953-F3CB-4152-894D-09C541805AD4}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@ -63,6 +65,10 @@ Global
{4E2CC4E4-F109-4876-8498-912E13905765}.Debug|Any CPU.Build.0 = Debug|Any CPU {4E2CC4E4-F109-4876-8498-912E13905765}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E2CC4E4-F109-4876-8498-912E13905765}.Release|Any CPU.ActiveCfg = Release|Any CPU {4E2CC4E4-F109-4876-8498-912E13905765}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E2CC4E4-F109-4876-8498-912E13905765}.Release|Any CPU.Build.0 = Release|Any CPU {4E2CC4E4-F109-4876-8498-912E13905765}.Release|Any CPU.Build.0 = Release|Any CPU
{41169953-F3CB-4152-894D-09C541805AD4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41169953-F3CB-4152-894D-09C541805AD4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41169953-F3CB-4152-894D-09C541805AD4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{41169953-F3CB-4152-894D-09C541805AD4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE