Просмотр исходного кода

移除多余的数据库支持

懒得勤快 3 лет назад
Родитель
Сommit
b8ea95c5fe

+ 2 - 13
src/Masuit.MyBlogs.Core/Common/ImagebedClient.cs

@@ -1,4 +1,5 @@
-using Hangfire;
+using Collections.Pooled;
+using Hangfire;
 using Masuit.MyBlogs.Core.Configs;
 using Masuit.Tools;
 using Masuit.Tools.Html;
@@ -7,8 +8,6 @@ using Masuit.Tools.Systems;
 using System.Net.Http.Headers;
 using System.Text.RegularExpressions;
 using System.Web;
-using Collections.Pooled;
-using ImageMagick;
 
 namespace Masuit.MyBlogs.Core.Common
 {
@@ -46,16 +45,6 @@ namespace Masuit.MyBlogs.Core.Common
                 return Task.FromResult<(string, bool)>((null, false));
             }
 
-            var optimizer = new ImageOptimizer
-            {
-                IgnoreUnsupportedFormats = true,
-                OptimalCompression = true
-            };
-            if (optimizer.IsSupported(stream))
-            {
-                optimizer.LosslessCompress(stream);
-            }
-
             file = Regex.Replace(Path.GetFileName(file), @"\p{P}|\p{S}", "");
             using var gitlabs = AppConfig.GitlabConfigs.Where(c => c.FileLimitSize >= stream.Length && !_failedList.Contains(c.ApiUrl)).OrderByRandom().ToPooledList();
             if (gitlabs.Count > 0)

+ 8 - 6
src/Masuit.MyBlogs.Core/Common/PerfCounter.cs

@@ -1,14 +1,15 @@
-using System.ComponentModel.DataAnnotations;
-using System.ComponentModel.DataAnnotations.Schema;
-using System.Diagnostics;
-using System.Net.Sockets;
-using Masuit.MyBlogs.Core.Infrastructure;
+using Masuit.MyBlogs.Core.Infrastructure;
 using Masuit.Tools;
 using Masuit.Tools.DateTimeExt;
 using Masuit.Tools.Hardware;
+using Masuit.Tools.Logging;
 using Masuit.Tools.Systems;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.DependencyInjection.Extensions;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+using System.Diagnostics;
+using System.Net.Sockets;
 
 namespace Masuit.MyBlogs.Core.Common;
 
@@ -33,8 +34,10 @@ public interface IPerfCounter
                 {
                     if (errorCount > 20)
                     {
+                        LogManager.Error(e);
                         break;
                     }
+
                     Console.ForegroundColor = ConsoleColor.Red;
                     Console.WriteLine(e.Message);
                     Console.ForegroundColor = ConsoleColor.White;
@@ -180,7 +183,6 @@ public class PerformanceCounter
     /// <summary>
     /// 当前时间戳
     /// </summary>
-    [HypertableColumn]
     public long Time { get; set; }
 
     /// <summary>

+ 2 - 1
src/Masuit.MyBlogs.Core/Controllers/AdvertisementController.cs

@@ -68,7 +68,8 @@ namespace Masuit.MyBlogs.Core.Controllers
             Expression<Func<Advertisement, bool>> where = p => true;
             if (!string.IsNullOrEmpty(kw))
             {
-                where = where.And(p => p.Title.Contains(kw) || p.Description.Contains(kw) || p.Url.Contains(kw));
+                kw = Regex.Escape(kw);
+                where = where.And(p => Regex.IsMatch(p.Title + p.Description + p.Url, kw, RegexOptions.IgnoreCase));
             }
 
             var list = AdsService.GetQuery(where).OrderByDescending(p => p.Status == Status.Available).ThenByDescending(a => a.Price).ThenByDescending(a => a.Id).ProjectTo<AdvertisementViewModel>(MapperConfig).NotCacheable().ToPagedList(page, size);

+ 0 - 20
src/Masuit.MyBlogs.Core/Controllers/HealthController.cs

@@ -1,20 +0,0 @@
-using Microsoft.AspNetCore.Mvc;
-
-namespace Masuit.MyBlogs.Core.Controllers
-{
-    /// <summary>
-    /// 健康检查
-    /// </summary>
-    public class HealthController : Controller
-    {
-        /// <summary>
-        /// 心跳检测
-        /// </summary>
-        /// <returns></returns>
-        [Route("health")]
-        public OkResult Check()
-        {
-            return Ok();
-        }
-    }
-}

+ 42 - 44
src/Masuit.MyBlogs.Core/Infrastructure/LoggerDbContext.cs

@@ -1,8 +1,6 @@
-using Masuit.MyBlogs.Core.Models.Entity;
+using Masuit.MyBlogs.Core.Common;
+using Masuit.MyBlogs.Core.Models.Entity;
 using Microsoft.EntityFrameworkCore;
-using System.Reflection;
-using Masuit.MyBlogs.Core.Common;
-using Microsoft.EntityFrameworkCore.Metadata;
 
 namespace Masuit.MyBlogs.Core.Infrastructure;
 
@@ -24,44 +22,44 @@ public class LoggerDbContext : DbContext
     }
 }
 
-[AttributeUsage(AttributeTargets.Property)]
-public class HypertableColumnAttribute : Attribute
-{ }
+//[AttributeUsage(AttributeTargets.Property)]
+//public class HypertableColumnAttribute : Attribute
+//{ }
 
-public static class TimeScaleExtensions
-{
-    public static void ApplyHypertables(this DbContext context)
-    {
-        if (context.Database.IsNpgsql())
-        {
-            context.Database.ExecuteSqlRaw("CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;");
-            var entityTypes = context.Model.GetEntityTypes();
-            foreach (var entityType in entityTypes)
-            {
-                foreach (var property in entityType.GetProperties())
-                {
-                    if (property.PropertyInfo.GetCustomAttribute(typeof(HypertableColumnAttribute)) != null)
-                    {
-                        var tableName = entityType.GetTableName();
-                        var schema = entityType.GetSchema();
-                        var identifier = StoreObjectIdentifier.Table(tableName, schema);
-                        var columnName = property.GetColumnName(identifier);
-                        if (property.ClrType == typeof(DateTime))
-                        {
-                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}');");
-                        }
-                        else
-                        {
-                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}', chunk_time_interval => 604800000000);");
-                            context.Database.ExecuteSqlRaw($@"CREATE FUNCTION current_microfortnight() RETURNS BIGINT
-                            LANGUAGE SQL STABLE AS $$
-                               SELECT CAST(1209600 * EXTRACT(EPOCH FROM CURRENT_TIME) / 1000000 AS BIGINT)
-                             $$;
-                            SELECT set_integer_now_func('""{columnName}""', 'current_microfortnight');");
-                        }
-                    }
-                }
-            }
-        }
-    }
-}
+//public static class TimeScaleExtensions
+//{
+//    public static void ApplyHypertables(this DbContext context)
+//    {
+//        if (context.Database.IsNpgsql())
+//        {
+//            context.Database.ExecuteSqlRaw("CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;");
+//            var entityTypes = context.Model.GetEntityTypes();
+//            foreach (var entityType in entityTypes)
+//            {
+//                foreach (var property in entityType.GetProperties())
+//                {
+//                    if (property.PropertyInfo.GetCustomAttribute(typeof(HypertableColumnAttribute)) != null)
+//                    {
+//                        var tableName = entityType.GetTableName();
+//                        var schema = entityType.GetSchema();
+//                        var identifier = StoreObjectIdentifier.Table(tableName, schema);
+//                        var columnName = property.GetColumnName(identifier);
+//                        if (property.ClrType == typeof(DateTime))
+//                        {
+//                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}');");
+//                        }
+//                        else
+//                        {
+//                            context.Database.ExecuteSqlRaw($"SELECT create_hypertable('\"{tableName}\"', '{columnName}', chunk_time_interval => 604800000000);");
+//                            context.Database.ExecuteSqlRaw($@"CREATE FUNCTION current_microfortnight() RETURNS BIGINT
+//                            LANGUAGE SQL STABLE AS $$
+//                               SELECT CAST(1209600 * EXTRACT(EPOCH FROM CURRENT_TIME) / 1000000 AS BIGINT)
+//                             $$;
+//                            SELECT set_integer_now_func('""{columnName}""', 'current_microfortnight');");
+//                        }
+//                    }
+//                }
+//            }
+//        }
+//    }
+//}

+ 1 - 4
src/Masuit.MyBlogs.Core/Masuit.MyBlogs.Core.csproj

@@ -54,22 +54,19 @@
         <PackageReference Include="htmldiff.net-core" Version="1.3.6" />
         <PackageReference Include="IP2Region" Version="1.2.0" />
         <PackageReference Include="Karambolo.AspNetCore.Bundling.NUglify" Version="3.5.1" />
-        <PackageReference Include="Magick.NET-Q8-AnyCPU" Version="12.0.1" />
         <PackageReference Include="Masuit.Tools.Excel" Version="1.2.2" />
         <PackageReference Include="MaxMind.GeoIP2" Version="5.1.0" />
         <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.8" />
         <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.8" />
         <PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="6.0.8" />
-        <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.8" />
         <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="6.0.8" />
-        <PackageReference Include="Microsoft.Graph" Version="4.36.0" />
+        <PackageReference Include="Microsoft.Graph" Version="4.38.0" />
         <PackageReference Include="Microsoft.Graph.Auth" Version="1.0.0-preview.7" />
         <PackageReference Include="MiniProfiler.AspNetCore.Mvc" Version="4.2.22" />
         <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.6" />
         <PackageReference Include="OpenXmlPowerTools-NetStandard" Version="4.6.23-alpha4" />
         <PackageReference Include="MiniProfiler.EntityFrameworkCore" Version="4.2.22" />
         <PackageReference Include="PanGu.HighLight" Version="1.0.0" />
-        <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.2" />
         <PackageReference Include="SixLabors.ImageSharp.Web" Version="2.0.2" />
         <PackageReference Include="System.Linq.Dynamic.Core" Version="1.2.19" />
         <PackageReference Include="TimeZoneConverter" Version="5.0.0" />

+ 4 - 5
src/Masuit.MyBlogs.Core/Models/Entity/RequestLogDetail.cs

@@ -1,8 +1,7 @@
-using System.ComponentModel.DataAnnotations;
-using System.ComponentModel.DataAnnotations.Schema;
-using Masuit.MyBlogs.Core.Infrastructure;
-using Masuit.Tools.Systems;
+using Masuit.Tools.Systems;
 using Microsoft.EntityFrameworkCore;
+using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
 
 namespace Masuit.MyBlogs.Core.Models.Entity;
 
@@ -17,7 +16,7 @@ public class RequestLogDetail
     [StringLength(32)]
     public string Id { get; set; }
 
-    [Column(TypeName = "timestamp"), HypertableColumn]
+    [Column(TypeName = "timestamp")]
     public DateTime Time { get; set; }
 
     [StringLength(1024), Unicode]

+ 5 - 50
src/Masuit.MyBlogs.Core/Startup.cs

@@ -84,50 +84,8 @@ namespace Masuit.MyBlogs.Core
         public void ConfigureServices(IServiceCollection services)
         {
             services.AddEFSecondLevelCache(options => options.UseCustomCacheProvider<MyEFCacheManagerCoreProvider>(CacheExpirationMode.Absolute, TimeSpan.FromMinutes(5)).DisableLogging(true));
-            services.AddDbContext<DataContext>((serviceProvider, opt) =>
-            {
-                switch (Configuration["Database:Provider"])
-                {
-                    case "pgsql":
-                        opt.UseNpgsql(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(10));
-                        break;
-
-                    case "mysql":
-                        opt.UseMySql(AppConfig.ConnString, ServerVersion.AutoDetect(AppConfig.ConnString), builder => builder.EnableRetryOnFailure(10));
-                        break;
-
-                    case "mssql":
-                        opt.UseSqlServer(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(10));
-                        break;
-
-                    case "sqlite":
-                        opt.UseSqlite(AppConfig.ConnString);
-                        break;
-                }
-
-                opt.AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>()).EnableSensitiveDataLogging();
-            }); //配置数据库
-            services.AddDbContext<LoggerDbContext>(opt =>
-            {
-                switch (Configuration["Database:Provider"])
-                {
-                    case "pgsql":
-                        opt.UseNpgsql(AppConfig.ConnString);
-                        break;
-
-                    case "mysql":
-                        opt.UseMySql(AppConfig.ConnString, ServerVersion.AutoDetect(AppConfig.ConnString), builder => builder.EnableRetryOnFailure(10));
-                        break;
-
-                    case "mssql":
-                        opt.UseSqlServer(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(10));
-                        break;
-
-                    case "sqlite":
-                        opt.UseSqlite(AppConfig.ConnString);
-                        break;
-                }
-            }); //配置数据库
+            services.AddDbContext<DataContext>((serviceProvider, opt) => opt.UseNpgsql(AppConfig.ConnString, builder => builder.EnableRetryOnFailure(10)).AddInterceptors(serviceProvider.GetRequiredService<SecondLevelCacheInterceptor>()).EnableSensitiveDataLogging()); //配置数据库
+            services.AddDbContext<LoggerDbContext>(opt => opt.UseNpgsql(AppConfig.ConnString)); //配置数据库
             services.ConfigureOptions();
             services.AddHttpsRedirection(options =>
             {
@@ -173,7 +131,7 @@ namespace Masuit.MyBlogs.Core
             services.AutoRegisterServices();
             services.AddRazorPages();
             services.AddServerSideBlazor();
-            services.AddMapper().AddMyMvc();
+            services.AddMapper().AddMyMvc().AddHealthChecks();
             services.AddImageSharp(options =>
                 {
                     options.MemoryStreamManager = new RecyclableMemoryStreamManager();
@@ -217,11 +175,7 @@ namespace Masuit.MyBlogs.Core
         {
             ServiceProvider = app.ApplicationServices;
             maindb.Database.EnsureCreated();
-            if (loggerdb.Database.EnsureCreated())
-            {
-                loggerdb.ApplyHypertables();
-            }
-
+            loggerdb.Database.EnsureCreated();
             app.InitSettings();
             app.UseLuceneSearch(env, hangfire, luceneIndexerOptions);
             app.UseForwardedHeaders().UseCertificateForwarding(); // X-Forwarded-For
@@ -255,6 +209,7 @@ namespace Masuit.MyBlogs.Core
                     options.LongPolling.PollTimeout = TimeSpan.FromSeconds(10);
                     options.TransportMaxBufferSize = 8388608;
                 });
+                endpoints.MapHealthChecks("/health");
                 endpoints.MapControllers(); // 属性路由
                 endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}"); // 默认路由
                 endpoints.MapFallbackToController("Index", "Error");

+ 0 - 2
src/Masuit.MyBlogs.Core/appsettings.json

@@ -13,8 +13,6 @@
         "CertPassword": "cEHlnUGu" // 证书密码
     },
     "Database": {
-        "Provider": "pgsql", //mysql,pgsql,mssql,sqlite
-        //"ConnString": "Server=127.0.0.1;Port=3306;Database=MyBlogs;Uid=root;Pwd=;Charset=utf8mb4", // 数据库连接字符串
         "ConnString": "Host=127.1;Username=postgres;Password=1;Database=myblogs" // 数据库连接字符串
     },
     "Redis": "127.0.0.1:6379,allowadmin=true,connectTimeout=20000,connectRetry=1,responseTimeout=20000,syncTimeout=10000", // Redis连接字符串