开启https,接入grpc

This commit is contained in:
wenyongda 2025-06-13 16:40:50 +08:00
parent 07a6c2af8a
commit a2cb96b9a7
12 changed files with 387 additions and 151 deletions

1
.gitignore vendored
View File

@ -286,3 +286,4 @@ __pycache__/
/ZRAdmin-vue/deploy.js
/ZR.Admin.WebApi/ZRModel.xml
ZRAdmin-vue/dist.zip
**/.vshistory/

View File

@ -0,0 +1,35 @@
syntax = "proto3";
option csharp_namespace = "ZR.Admin.Grpc";
package my.diary;
import "google/protobuf/timestamp.proto";
// The greeting service definition.
service MyDiary {
// Sends a greeting
rpc Edit (EditRequest) returns (EditReply);
rpc Query (QueryRequest) returns (QueryReply);
}
// The request message containing the user's name.
message EditRequest {
string content = 1;
int64 user_id = 2;
google.protobuf.Timestamp create_time = 3; // 使 snake_case
}
// The response message containing the greetings.
message EditReply {
string result_message = 1;
}
message QueryRequest {
int64 user_id = 1;
google.protobuf.Timestamp create_time = 2;
}
message QueryReply {
string content = 1;
}

View File

@ -0,0 +1,37 @@
using Grpc.Core;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZR.Admin.Grpc.Services
{
public class GreeterService : Greeter.GreeterBase
{
private readonly ILogger<GreeterService> _logger;
public GreeterService(ILogger<GreeterService> logger)
{
_logger = logger;
}
// 实现 SayHello 方法
// 第一个参数是请求消息 (HelloRequest)
// 第二个参数是服务器上下文 (ServerCallContext),提供关于当前调用的信息
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
_logger.LogInformation($"接收到来自 {request.Name} 的请求");
// 构建并返回回复消息
var reply = new HelloReply
{
Message = $"你好,{request.Name} 来自 gRPC 服务器!"
};
// 返回一个 Task<HelloReply>
return Task.FromResult(reply);
}
}
}

View File

@ -0,0 +1,76 @@
using Grpc.Core;
using Microsoft.Extensions.Logging;
using ZR.Service.IService;
namespace ZR.Admin.Grpc.Services
{
public class MyDiaryService(ILogger<MyDiaryService> logger, IMyDiaryService myDiaryService) : MyDiary.MyDiaryBase
{
public override async Task<EditReply> Edit(EditRequest request, ServerCallContext context)
{
logger.LogInformation($"接收到来自 {request.UserId} 的请求");
var myDiary = new Model.MyDiary()
{
Content = request.Content,
CreateTime = request.CreateTime.ToDateTime().ToLocalTime(),
UserId = request.UserId
};
var myDiaryToday = await myDiaryService.Queryable()
.Where(it => it.CreateTime.Date == myDiary.CreateTime.Date && it.UserId == myDiary.UserId)
.FirstAsync();
if (myDiaryToday != null)
{
myDiaryToday.Content = myDiary.Content;
await myDiaryService.Updateable(myDiaryToday)
.ExecuteCommandAsync();
}
else
{
await myDiaryService.Insertable(myDiary).ExecuteReturnSnowflakeIdAsync();
}
// 构建并返回回复消息
var reply = new EditReply()
{
ResultMessage = $"日记已记录 来自 gRPC 服务器!"
};
logger.LogInformation($"日记已记录");
// 返回一个 Task<HelloReply>
return reply;
}
public override async Task<QueryReply> Query(QueryRequest request, ServerCallContext context)
{
logger.LogInformation($"接收到来自 {request.UserId} 的请求");
var myDiary = new Model.MyDiary()
{
CreateTime = request.CreateTime.ToDateTime().ToLocalTime(),
UserId = request.UserId
};
var myDiaryToday = await myDiaryService.Queryable()
.Where(it => it.CreateTime.Date == myDiary.CreateTime.Date && it.UserId == myDiary.UserId)
.FirstAsync();
if (myDiaryToday != null)
{
myDiary.Content = myDiaryToday.Content;
}
// 构建并返回回复消息
var reply = new QueryReply()
{
Content = myDiary.Content ?? ""
};
return reply;
}
}
}

View File

@ -7,16 +7,17 @@
</PropertyGroup>
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Both"/>
<Protobuf Include="Protos\block.proto" GrpcServices="Client"/>
<Protobuf Include="Protos\greet.proto" GrpcServices="Both" />
<Protobuf Include="Protos\block.proto" GrpcServices="Client" />
<Protobuf Include="Protos\my_diary.proto" GrpcServices="Server" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Grpc.AspNetCore" Version="2.49.0"/>
<PackageReference Include="Grpc.AspNetCore" Version="2.49.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
<ProjectReference Include="..\ZR.Service\ZR.Service.csproj" />
</ItemGroup>
</Project>

View File

@ -1,14 +1,15 @@
using AspNetCoreRateLimit;
using Infrastructure.Converter;
using Microsoft.AspNetCore.DataProtection;
using NLog.Web;
using System.Text.Json;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Redis;
using Microsoft.Extensions.Options;
using NLog.Web;
using System.Text.Json;
using ZR.Admin.Grpc;
using ZR.Admin.Grpc.Extensions;
using ZR.Admin.Grpc.Services;
using ZR.Admin.WebApi.Extensions;
using ZR.Infrastructure.Cache;
using ZR.Infrastructure.WebExtensions;
@ -99,15 +100,27 @@ builder.Services.AddSignalR()
options.PayloadSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
});
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);
//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);
//builder.Services.AddGrpcServiceConfiguration(builder.Configuration);
// 配置 Kestrel 监听 HTTP/2 的非加密流量
//builder.WebHost.ConfigureKestrel(options =>
//{
// // 如果你只想监听一个端口,只保留其中一个 Listen
// options.ListenLocalhost(8888, o =>
// {
// o.Protocols = HttpProtocols.Http2; // 明确设置为 Http2
// });
//});
var app = builder.Build();
InternalApp.ServiceProvider = app.Services;
InternalApp.Configuration = builder.Configuration;
@ -140,7 +153,7 @@ app.UseStaticFiles();
//开启路由访问
app.UseRouting();
app.UseCors("Policy");//要放在app.UseEndpoints前。
//app.UseHttpsRedirection();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
@ -187,12 +200,15 @@ using (var serviceScope = app.Services.CreateScope())
pol.IpRules.AddRange(ipRateLimitPolicies.Adapt<List<IpRateLimitPolicy>>());
await ipPolicyStore.SetAsync(optionsAccessor.Value.IpPolicyPrefix, pol);
// var greeterClient = services.GetRequiredService<Greeter.GreeterClient>();
// var helloReply = await greeterClient.SayHelloAsync(new HelloRequest
// {
//var greeterClient = services.GetRequiredService<Greeter.GreeterClient>();
//var helloReply = await greeterClient.SayHelloAsync(new HelloRequest
//{
// Name = "gree"
// });
// Console.WriteLine(helloReply);
//});
//Console.WriteLine(helloReply);
}
app.MapGrpcService<GreeterService>();
app.MapGrpcService<MyDiaryService>();
app.Run();

View File

@ -13,7 +13,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchUrl": "",
"applicationUrl": "http://localhost:8888",
"applicationUrl": "https://localhost:8888",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -0,0 +1,20 @@
{
"urls": "http://[*]:8888", //urldevServer
"dbConfigs": [
{
"Conn": "server=8.140.174.251;user=admin;pwd=admin123;database=ZrAdmin",
"DbType": 0, // MySql = 0, SqlServer = 1, Oracle = 3PgSql = 4
"ConfigId": "0", //
"IsAutoCloseConnection": true
}
//...
],
//redis
"RedisServer": {
"open": 1, //redis
"Cache": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
// "Cache": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
"Session": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
// "Session": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
},
}

View File

@ -8,7 +8,7 @@
},
"dbConfigs": [
{
"Conn": "server=8.140.174.251;user=admin;pwd=admin123;database=ZrAdmin;port=33060",
"Conn": "server=127.0.0.1;user=admin;pwd=admin123;database=ZrAdmin;port=3306",
"DbType": 0, // MySql = 0, SqlServer = 1, Oracle = 3PgSql = 4
"ConfigId": "0", //
"IsAutoCloseConnection": true
@ -18,26 +18,26 @@
//
"CodeGenDbConfig": {
//{dbName}
"Conn": "Data Source=LAPTOP-STKF2M8H\\SQLEXPRESS;User ID=admin;Password=admin123;Initial Catalog={dbName};",
"DbType": 1,
"Conn": "Data Source=127.0.0.1;user=admin;pwd=admin123;database=ZrAdmin;port=3306",
"DbType": 0,
"IsAutoCloseConnection": true,
"DbName": "ZrAdmin" //,Oracle
},
"urls": "http://localhost:8888", //urldevServer
"urls": "https://localhost:8888", //urldevServer
"corsUrls": [ "http://localhost:8887", "http://localhost:8886" ], //","
"JwtSettings": {
"Issuer": "ZRAdmin.NET", //token
"Audience": "ZRAdmin.NET", //token
"SecretKey": "SecretKey-ZRADMIN.NET-20210101",
"Expire": 1440, //jwt
"RefreshTokenTime": 5,//
"RefreshTokenTime": 5, //
"TokenType": "Bearer"
},
"InjectClass": [ "ZR.Repository", "ZR.Service", "ZR.Tasks", "ZR.ServiceCore" ], //
"ShowDbLog": true, //db
"InitDb": false, //db
"DemoMode": false, //
"SingleLogin": false,//
"SingleLogin": false, //
"Upload": {
"uploadUrl": "http://localhost:8888", //访
"localSavePath": "", // wwwroot
@ -102,10 +102,8 @@
//redis
"RedisServer": {
"open": 1, //redis
"Cache": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
// "Cache": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
"Session": "8.140.174.251:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
// "Session": "127.0.0.1:6379,password=Wyd210213,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
"Cache": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=cache:",
"Session": "127.0.0.1:6379,defaultDatabase=0,poolsize=50,ssl=false,writeBuffer=10240,prefix=session:"
},
//
"CaptchaOptions": {

23
ZR.Model/MyDiary.cs Normal file
View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZR.Model
{
[SugarTable("my_diary")]
public class MyDiary
{
[SugarColumn(IsPrimaryKey = true)]
[JsonConverter(typeof(ValueToStringConverter))]
public long Id { get; set; }
public string Content { get; set; }
[JsonConverter(typeof(ValueToStringConverter))]
public long UserId { get; set; }
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model;
namespace ZR.Service.IService
{
public interface IMyDiaryService : IBaseService<MyDiary>
{
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model;
using ZR.Service.IService;
namespace ZR.Service
{
[AppService(ServiceType = typeof(IMyDiaryService), ServiceLifetime = LifeTime.Transient)]
public class MyDiaryService : BaseService<MyDiary>, IMyDiaryService
{
}
}