Tiobon.Core.Jobs

master
xiaochanghai 8 months ago
parent 2b9e3d115d
commit e75003f555
  1. 2
      Tiobon.Core.Api/Program.cs
  2. 13
      Tiobon.Core.Common/DB/BaseDBConfig.cs
  3. 163
      Tiobon.Core.Common/Extensions/Check.cs
  4. 92
      Tiobon.Core.Common/Extensions/TypeExtensions.cs
  5. 1
      Tiobon.Core.Common/Tiobon.Core.Common.csproj
  6. 70
      Tiobon.Core.Jobs/Helper.cs
  7. 21
      Tiobon.Core.Jobs/Program.cs
  8. 44
      Tiobon.Core.Jobs/TaskCenter.cs
  9. 29
      Tiobon.Core.Jobs/Tiobon.Core.Jobs.csproj
  10. 9
      Tiobon.Core.Jobs/appsettings.Development.json
  11. 372
      Tiobon.Core.Jobs/appsettings.json
  12. BIN
      Tiobon.Core.Jobs/favicon.ico
  13. 39
      Tiobon.Core.Services/Extensions/AppServiceExtensions.cs
  14. 2
      Tiobon.Core.Tasks/QuartzNet/ISchedulerCenter.cs
  15. 63
      Tiobon.Core.Tasks/QuartzNet/SchedulerCenterServer.cs
  16. 3
      Tiobon.Core.Tasks/Tiobon.Core.Tasks.csproj
  17. 6
      Tiobon.Core.sln

@ -56,7 +56,7 @@ builder.Services.AddCacheSetup();
builder.Services.AddSqlsugarSetup();
builder.Services.AddDbSetup();
builder.Services.AddInitializationHostServiceSetup();
builder.Services.AddSimpleDapperSetup();
builder.Services.c();
builder.Host.AddSerilogSetup();

@ -106,6 +106,19 @@ namespace Tiobon.Core.Common.DB
return mutiDBOperate;
}
public static MutiDBOperate GetMainConnectionDb()
{
var mainConnetctDb = MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
if (MutiConnectionString.allDbs.Count > 0)
{
if (mainConnetctDb == null)
mainConnetctDb = MutiConnectionString.allDbs[0];
}
else
throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;");
return mainConnetctDb;
}
}

@ -0,0 +1,163 @@
using JetBrains.Annotations;
using System.Diagnostics;
namespace Tiobon.Core.Common;
[DebuggerStepThrough]
public static class Check
{
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName)
{
if (value == null)
{
throw new ArgumentNullException(parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static T NotNull<T>(
T value,
[InvokerParameterName][NotNull] string parameterName,
string message)
{
if (value == null)
{
throw new ArgumentNullException(parameterName, message);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNull(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (value == null)
{
throw new ArgumentException($"{parameterName} can not be null!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrWhiteSpace(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException($"{parameterName} can not be null, empty or white space!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static string NotNullOrEmpty(
string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength = int.MaxValue,
int minLength = 0)
{
if (value.IsNullOrEmpty())
{
throw new ArgumentException($"{parameterName} can not be null or empty!", parameterName);
}
if (value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
if (minLength > 0 && value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
return value;
}
[ContractAnnotation("value:null => halt")]
public static ICollection<T> NotNullOrEmpty<T>(ICollection<T> value, [InvokerParameterName][NotNull] string parameterName)
{
if (value == null || value.Count <= 0)
{
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
}
return value;
}
[ContractAnnotation("type:null => halt")]
public static Type AssignableTo<TBaseType>(
Type type,
[InvokerParameterName][NotNull] string parameterName)
{
NotNull(type, parameterName);
if (!type.IsAssignableTo<TBaseType>())
{
throw new ArgumentException($"{parameterName} (type of {type.AssemblyQualifiedName}) should be assignable to the {typeof(TBaseType).GetFullNameWithAssemblyName()}!");
}
return type;
}
public static string Length(
[CanBeNull] string value,
[InvokerParameterName][NotNull] string parameterName,
int maxLength,
int minLength = 0)
{
if (minLength > 0)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(parameterName + " can not be null or empty!", parameterName);
}
if (value.Length < minLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or bigger than {minLength}!", parameterName);
}
}
if (value != null && value.Length > maxLength)
{
throw new ArgumentException($"{parameterName} length must be equal to or lower than {maxLength}!", parameterName);
}
return value;
}
}

@ -0,0 +1,92 @@
using Tiobon.Core.Common;
using JetBrains.Annotations;
namespace System;
public static class TypeExtensions
{
public static string GetFullNameWithAssemblyName(this Type type)
{
return type.FullName + ", " + type.Assembly.GetName().Name;
}
/// <summary>
/// Determines whether an instance of this type can be assigned to
/// an instance of the <typeparamref name="TTarget"></typeparamref>.
///
/// Internally uses <see cref="Type.IsAssignableFrom"/>.
/// </summary>
/// <typeparam name="TTarget">Target type</typeparam> (as reverse).
public static bool IsAssignableTo<TTarget>([NotNull] this Type type)
{
Check.NotNull(type, nameof(type));
return type.IsAssignableTo(typeof(TTarget));
}
/// <summary>
/// Determines whether an instance of this type can be assigned to
/// an instance of the <paramref name="targetType"></paramref>.
///
/// Internally uses <see cref="Type.IsAssignableFrom"/> (as reverse).
/// </summary>
/// <param name="type">this type</param>
/// <param name="targetType">Target type</param>
public static bool IsAssignableTo([NotNull] this Type type, [NotNull] Type targetType)
{
Check.NotNull(type, nameof(type));
Check.NotNull(targetType, nameof(targetType));
return targetType.IsAssignableFrom(type);
}
/// <summary>
/// Gets all base classes of this type.
/// </summary>
/// <param name="type">The type to get its base classes.</param>
/// <param name="includeObject">True, to include the standard <see cref="object"/> type in the returned array.</param>
public static Type[] GetBaseClasses([NotNull] this Type type, bool includeObject = true)
{
Check.NotNull(type, nameof(type));
var types = new List<Type>();
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject);
return types.ToArray();
}
/// <summary>
/// Gets all base classes of this type.
/// </summary>
/// <param name="type">The type to get its base classes.</param>
/// <param name="stoppingType">A type to stop going to the deeper base classes. This type will be be included in the returned array</param>
/// <param name="includeObject">True, to include the standard <see cref="object"/> type in the returned array.</param>
public static Type[] GetBaseClasses([NotNull] this Type type, Type stoppingType, bool includeObject = true)
{
Check.NotNull(type, nameof(type));
var types = new List<Type>();
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject, stoppingType);
return types.ToArray();
}
private static void AddTypeAndBaseTypesRecursively(
[NotNull] List<Type> types,
[CanBeNull] Type type,
bool includeObject,
[CanBeNull] Type stoppingType = null)
{
if (type == null || type == stoppingType)
{
return;
}
if (!includeObject && type == typeof(object))
{
return;
}
AddTypeAndBaseTypesRecursively(types, type.BaseType, includeObject, stoppingType);
types.Add(type);
}
}

@ -19,6 +19,7 @@
<ItemGroup>
<PackageReference Include="AgileObjects.AgileMapper" Version="1.8.1" />
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0" />
<PackageReference Include="Magicodes.IE.Excel" Version="2.7.4.5" />
<PackageReference Include="InitQ" Version="1.0.0.18" />
<PackageReference Include="log4net" Version="2.0.15" />

@ -0,0 +1,70 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using Tiobon.Core.Common;
using Tiobon.Core.Common.DB;
using Tiobon.Core.Common.Seed;
using Tiobon.Core.Repository.UnitOfWorks;
using Autofac;
using Tiobon.Core.Extensions;
using Tiobon.Core.Services.Extensions;
using Tiobon.Core.DataAccess;
using Microsoft.EntityFrameworkCore;
using Tiobon.Core.Extensions.HostedService;
using Tiobon.Core.Common.DB.Dapper.Extensions;
namespace Tiobon.Core.Jobs;
/// <summary>
/// 任务处理中心
/// </summary>
public class Helper
{
public static void Init(ServiceCollection services)
{
var basePath = AppContext.BaseDirectory;
services.AddSingleton(new AppSettings(basePath));
services.AddTransient<IUnitOfWorkManage, UnitOfWorkManage>();
services.AddScoped<DBSeed>();
services.AddScoped<MyContext>();
services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
{
return new SqlSugar.SqlSugarScope(new SqlSugar.ConnectionConfig()
{
ConnectionString = BaseDBConfig.GetMainConnectionDb().Connection, //必填, 数据库连接字符串
DbType = (SqlSugar.DbType)BaseDBConfig.GetMainConnectionDb().DbType, //必填, 数据库类型
IsAutoCloseConnection = true, //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
});
});
var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
services.AddDbContext<DataContext>(options =>
{
options.UseLazyLoadingProxies().UseSqlServer(mainConnetctDb.Connection, o => o.UseCompatibilityLevel(120));
});
var builder = new ContainerBuilder();
builder.RegisterType<UnitOfWorkManage>().As<IUnitOfWorkManage>()
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired();
builder.RegisterInstance(new LoggerFactory())
.As<ILoggerFactory>();
builder.RegisterGeneric(typeof(Logger<>))
.As(typeof(ILogger<>))
.SingleInstance();
services.AddAppServices();
//services.AddTransient<ISmQuartzJobServices, SmQuartzJobServices>();
//services.AddTransient<IBaseRepository<SmQuartzJob>, BaseRepository<SmQuartzJob>>();
//services.AddTransient<ISmQuartzJobLogServices, SmQuartzJobLogServices>();
//services.AddTransient<IBaseRepository<SmQuartzJobLog>, BaseRepository<SmQuartzJobLog>>();
// 注入事件服务
services.AddLogging();
services.AddJobSetup();
services.AddSimpleDapperSetup();
builder.Build();
}
}

@ -0,0 +1,21 @@
using Microsoft.Extensions.DependencyInjection;
using System.Threading;
using Tiobon.Core.Jobs;
using Tiobon.Core.Tasks;
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
Helper.Init(services);
var sp = services.BuildServiceProvider();
var schedulerCenter = sp.GetService<ISchedulerCenter>();
// 任务处理中心
TaskCenter taskCenter = new TaskCenter(schedulerCenter);
taskCenter.Start();
Thread.Sleep(Timeout.Infinite);
}
}

@ -0,0 +1,44 @@
using Microsoft.Extensions.DependencyInjection;
using Serilog.Core;
using System;
using Tiobon.Core.Common;
using Tiobon.Core.Tasks;
namespace Tiobon.Core.Jobs;
/// <summary>
/// 任务处理中心
/// </summary>
public class TaskCenter
{
private readonly ISchedulerCenter _schedulerCenter;
static TaskCenter()
{
//ReloadOnChange = true 当appsettings.json被修改时重新加载
}
/// <summary>
/// 初始化
/// </summary>
public TaskCenter(ISchedulerCenter schedulerCenter)
{
_schedulerCenter = schedulerCenter;
}
#region 启动任务服务
/// <summary>
/// 启动任务服务
/// </summary>
public void Start()
{
var container = new ServiceCollection();
_schedulerCenter.InitJobAsync();
}
#endregion
}

@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Exe</OutputType>
<ApplicationIcon>favicon.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.Development.json" />
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
<Content Include="favicon.ico" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Tiobon.Core.Extensions\Tiobon.Core.Extensions.csproj" />
<ProjectReference Include="..\Tiobon.Core.Services\Tiobon.Core.Services.csproj" />
<ProjectReference Include="..\Tiobon.Core.Tasks\Tiobon.Core.Tasks.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

@ -0,0 +1,372 @@
{
"urls": "http://*:9292", //webIIS
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Information",
"Microsoft.AspNetCore": "Warning",
"System": "Warning",
"System.Net.Http.HttpClient": "Warning",
"Hangfire": "Information",
"Magicodes": "Warning",
"DotNetCore.CAP": "Information",
"Savorboard.CAP": "Information",
"Quartz": "Information"
}
}
},
"AllowedHosts": "*",
"Redis": {
"Enable": false,
"ConnectionString": "127.0.0.1:6379",
"InstanceName": "" //
},
"RabbitMQ": {
"Enabled": true,
"Connection": "101xxxx57",
"UserName": "xxxx",
"Password": "xxxxx",
"Port": "5672",
"RetryCount": 2
},
"Kafka": {
"Enabled": false,
"Servers": "localhost:9092",
"Topic": "Tiobon",
"GroupId": "Tiobon-consumer",
"NumPartitions": 3 //
},
"EventBus": {
"Enabled": false,
"SubscriptionClientName": "Tiobon.Core"
},
"AppSettings": {
"CachingAOP": {
"Enabled": true
},
"LogToDb": true,
"LogAOP": {
"Enabled": false,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
}
},
"TranAOP": {
"Enabled": true
},
"UserAuditAOP": {
"Enabled": false
},
"SqlAOP": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
},
"LogToConsole": {
"Enabled": true
}
},
"Date": "2018-08-28",
"SeedDBEnabled": false, //
"SeedDBDataEnabled": false, //,
"Author": "Tiobon.Core",
"SvcName": "", // /svc/Tiobon
"UseLoadTest": false
},
//DB
//MainDbEnabledtrue
//Log:Enabledtrue
//Slaves,!SqlServer
//
//,
//,(+)
//ConnIdConnId+,ConnIdMain,ConnIdMian1
//!
//,
"MainDB": "WMTiobon_MSSQL_Main", //Enabledtrue
"DBS": [
/*
DBType
MySql = 0,
SqlServer = 1,
Sqlite = 2,
Oracle = 3,
PostgreSQL = 4,
Dm = 5,//
Kdbndp = 6,//
*/
{
"ConnId": "WMTiobon_MSSQL_Main",
"DBType": 1,
"Enabled": true,
"Connection": "Data Source=47.99.54.186;User ID=GHR;Password=Tiobon20190101;Database=GHR30;Encrypt=True;TrustServerCertificate=True;",
//"Connection": "Data Source=116.204.98.209;User ID=Tiobon;Password=&($!4UGUyU#$2sp9O;Database=Tiobon;Encrypt=True;TrustServerCertificate=True;",
"ProviderName": "System.Data.SqlClient"
},
{
"ConnId": "Main",
"DBType": 2,
"Enabled": false,
"Connection": "WMTiobon.db", //sqlite
"Slaves": [
{
"HitRate": 0, // 0使
"Connection": "WMTiobon2.db"
}
]
},
{
"ConnId": "Main2",
"DBType": 2,
"Enabled": false,
"Connection": "WMTiobon3.db", //sqlite
"Slaves": [
{
"HitRate": 0, // 0使
"Connection": "WMTiobon4.db"
}
]
},
{
"ConnId": "Log", //,
"DBType": 1,
"Enabled": true,
"HitRate": 50,
"Connection": "Data Source=47.99.54.186;User ID=GHR;Password=Tiobon20190101;Database=GHR30;Encrypt=True;TrustServerCertificate=True;",
"ProviderName": "System.Data.SqlClient"
},
{
"ConnId": "WMTiobon_MSSQL_1",
"DBType": 1,
"Enabled": false,
"Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMTiobon_MSSQL_1;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
"ProviderName": "System.Data.SqlClient"
},
{
"ConnId": "WMTiobon_MSSQL_2",
"DBType": 1,
"Enabled": false,
"Connection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=WMTiobon_MSSQL_2;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False",
"ProviderName": "System.Data.SqlClient"
},
{
"ConnId": "WMTiobon_MYSQL",
"DBType": 0,
"Enabled": false,
"Connection": "server=localhost;Database=Tiobon;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
},
{
"ConnId": "WMTiobon_MYSQL_2",
"DBType": 0,
"Enabled": false,
"Connection": "server=localhost;Database=Tioboncore001;Uid=root;Pwd=root;Port=3306;Allow User Variables=True;"
},
{
"ConnId": "WMTiobon_ORACLE",
"DBType": 3,
"Enabled": false,
"Connection": "Data Source=127.0.0.1/ops;User ID=OPS;Password=123456;Persist Security Info=True;Connection Timeout=60;"
},
{
"ConnId": "WMTiobon_DM",
"DBType": 5,
"Enabled": false,
"Connection": "Server=xxxxx:5236;User Id=xxxxx;PWD=xxxxx;SCHEMA=TESTDBA;"
},
{
"ConnId": "WMTiobon_KDBNDP",
"DBType": 6,
"Enabled": false,
"Connection": "Server=127.0.0.1;Port=54321;UID=SYSTEM;PWD=system;database=SQLSUGAR4XTEST1;"
}
],
"Audience": {
"Secret": "sdfsdfsrty45634kkhllghtdgdfss345t678fs", //16+
"SecretFile": "C:\\my-file\\Tiobon.core.audience.secret.txt", //Secret
"Issuer": "Tiobon.Core", //
"Audience": "wr", //
"ExpirationHour": 72 //
},
"Mongo": {
"ConnectionString": "mongodb://nosql.data",
"Database": "TiobonCoreDb"
},
"Startup": {
"Domain": "http://localhost:9291",
"Cors": {
"PolicyName": "CorsIpAccess", //
"EnableAllIPs": false, //trueIP访
// /localhost:8000/
// http://127.0.0.1:1818 http://localhost:1818
"IPs": "http://127.0.0.1:2364,http://localhost:2364,http://127.0.0.1:6688,http://localhost:6688"
},
"AppConfigAlert": {
"Enabled": true
},
"IdentityServer4": {
"Enabled": false, // false使jwttrue使Ids4
"AuthorizationUrl": "http://localhost:5004", //
"ApiName": "Tiobon.core.api" //
},
"Authing": {
"Enabled": false,
"Issuer": "https://uldr24esx31h-demo.authing.cn/oidc",
"Audience": "63d51c4205c2849803be5178",
"JwksUri": "https://uldr24esx31h-demo.authing.cn/oidc/.well-known/jwks.json"
},
"RedisMq": {
"Enabled": false //redis
},
"MiniProfiler": {
"Enabled": false //
},
"Nacos": {
"Enabled": false //Nacos
}
},
"Middleware": {
"RequestResponseLog": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
}
},
"IPLog": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
}
},
"RecordAccessLogs": {
"Enabled": true,
"LogToFile": {
"Enabled": true
},
"LogToDB": {
"Enabled": true
},
"IgnoreApis": "/api/permission/getnavigationbar,/api/monitor/getids4users,/api/monitor/getaccesslogs,/api/monitor/server,/api/monitor/getactiveusers,/api/monitor/server,"
},
"SignalR": {
"Enabled": false
},
"SignalRSendLog": {
"Enabled": false
},
"QuartzNetJob": {
"Enabled": true
},
"Consul": {
"Enabled": false
},
"IpRateLimit": {
"Enabled": false
},
"EncryptionResponse": {
"Enabled": true,
"AllApis": false,
"LimitApis": [
"/api/Login/GetJwtTokenSecret"
]
},
"EncryptionRequest": {
"Enabled": true,
"AllApis": false,
"LimitApis": [
"/api/Login/GetJwtTokenSecret"
]
}
},
"IpRateLimiting": {
"EnableEndpointRateLimiting": false, //False: globally executed, true: executed for each
"StackBlockedRequests": false, //False: Number of rejections should be recorded on another counter
"RealIpHeader": "X-Real-IP",
"ClientIdHeader": "X-ClientId",
"IpWhitelist": [], //
"EndpointWhitelist": [ "get:/api/xxx", "*:/api/yyy" ],
"ClientWhitelist": [ "dev-client-1", "dev-client-2" ],
"QuotaExceededResponse": {
"Content": "{{\"status\":429,\"msg\":\"访问过于频繁,请稍后重试\",\"success\":false}}",
"ContentType": "application/json",
"StatusCode": 429
},
"HttpStatusCode": 429, //
"GeneralRules": [ //api,*
{
"Endpoint": "*:/api/Tiobon*",
"Period": "1m",
"Limit": 20
},
{
"Endpoint": "*/api/*",
"Period": "1s",
"Limit": 3
},
{
"Endpoint": "*/api/*",
"Period": "1m",
"Limit": 30
},
{
"Endpoint": "*/api/*",
"Period": "12h",
"Limit": 500
}
]
},
"ConsulSetting": {
"ServiceName": "TiobonCoreService",
"ServiceIP": "localhost",
"ServicePort": "9291",
"ServiceHealthCheck": "/healthcheck",
"ConsulAddress": "http://localhost:8500"
},
"PayInfo": { //
"MERCHANTID": "", //
"POSID": "", //
"BRANCHID": "", //
"pubKey": "", //
"USER_ID": "", //
"PASSWORD": "", //
"OutAddress": "http://127.0.0.1:12345" //
},
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ], // nacos
"DefaultTimeOut": 15000, //
"Namespace": "public", //
"ListenInterval": 10000, //
"ServiceName": "Tiobon.Core.Api", //
"Port": "9291", //
"RegisterEnabled": true // nacos
},
"LogFiedOutPutConfigs": {
"tcpAddressHost": "", // elktcp
"tcpAddressPort": 0, // elktcp
"ConfigsInfo": [ // elk
{
"FiedName": "applicationName",
"FiedValue": "Tiobon.Core.Api"
}
]
},
"Seq": {
"Enabled": true,
"Address": "http://localhost:5341/",
"ApiKey": ""
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

@ -0,0 +1,39 @@
using Tiobon.Core.Repository.Base;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.Services.BASE;
namespace Tiobon.Core.Services.Extensions;
public static class AppServiceExtensions
{
public static IServiceCollection AddAppServices(this IServiceCollection services)
{
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
var types = Assembly.GetExecutingAssembly().GetTypes();
var assignedTypes = types
.Where(m => m.GetBaseClasses().Length > 1)
.ToList();
foreach (var assignedType in assignedTypes)
{
if (assignedType == typeof(BaseServices<,,,>))
{
continue;
}
// 添加 XXXService 依赖注入
services.AddScoped(assignedType);
// 添加 IXXXService -> XXXService 依赖注入
var interfaceType = assignedType.GetInterfaces().FirstOrDefault(i => i.Name[1..] == assignedType.Name);
if (interfaceType != null)
{
services.AddScoped(interfaceType, assignedType);
}
}
return services;
}
}

@ -73,6 +73,8 @@ namespace Tiobon.Core.Tasks
/// <returns></returns>
Task<ServiceResult<string>> ExecuteJobAsync(Ghre_TasksQz tasksQz);
Task<ServiceResult<string>> InitJobAsync();
}
}

@ -10,6 +10,10 @@ using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Tiobon.Core.Common.Helper;
using Tiobon.Core.Common;
using Tiobon.Core.Common.DB.Dapper;
namespace Tiobon.Core.Tasks
{
@ -125,7 +129,7 @@ namespace Tiobon.Core.Tasks
result.Message = $"该任务计划已经在执行:【{tasksQz.Name}】,请勿重复启动!";
return result;
}
if(tasksQz.TriggerType == 0 && tasksQz.CycleRunTimes != 0 && tasksQz.CycleHasRunTimes>=tasksQz.CycleRunTimes)
if (tasksQz.TriggerType == 0 && tasksQz.CycleRunTimes != 0 && tasksQz.CycleHasRunTimes >= tasksQz.CycleRunTimes)
{
result.Success = false;
result.Message = $"该任务计划已完成:【{tasksQz.Name}】,无需重复启动,如需启动请修改已循环次数再提交";
@ -209,14 +213,14 @@ namespace Tiobon.Core.Tasks
/// </summary>
/// <returns></returns>
public async Task<bool> IsExistScheduleJobAsync(Ghre_TasksQz sysSchedule)
{
{
JobKey jobKey = new JobKey(sysSchedule.Id.ToString(), sysSchedule.JobGroup);
if (await _scheduler.Result.CheckExists(jobKey))
{
{
return true;
}
else
{
{
return false;
}
}
@ -411,7 +415,7 @@ namespace Tiobon.Core.Tasks
.WithSimpleSchedule(x => x
.WithIntervalInSeconds(sysSchedule.IntervalSecond)
.WithRepeatCount(sysSchedule.CycleRunTimes - 1))
.EndAt(sysSchedule.EndTime.Value)
.EndAt(sysSchedule.EndTime.Value)
.Build();
return trigger;
}
@ -424,7 +428,7 @@ namespace Tiobon.Core.Tasks
.WithIntervalInSeconds(sysSchedule.IntervalSecond)
.RepeatForever()
)
.EndAt(sysSchedule.EndTime.Value)
.EndAt(sysSchedule.EndTime.Value)
.Build();
return trigger;
}
@ -461,13 +465,13 @@ namespace Tiobon.Core.Tasks
try
{
JobKey jobKey = new JobKey(tasksQz.Id.ToString(), tasksQz.JobGroup);
//判断任务是否存在,存在则 触发一次,不存在则先添加一个任务,触发以后再 停止任务
if (!await _scheduler.Result.CheckExists(jobKey))
{
//不存在 则 添加一个计划任务
await AddScheduleJobAsync(tasksQz);
//触发执行一次
await _scheduler.Result.TriggerJob(jobKey);
@ -493,5 +497,48 @@ namespace Tiobon.Core.Tasks
}
#region 初始化任务
/// <summary>
/// 初始化任务
/// </summary>
/// <returns></returns>
public async Task<ServiceResult<string>> InitJobAsync()
{
var result = new ServiceResult<string>();
try
{
if (AppSettings.app("Middleware", "QuartzNetJob", "Enabled").ObjToBool())
{
var allQzServices = DbAccess.QueryList<Ghre_TasksQz>("select * from Ghre_TasksQz");
foreach (var item in allQzServices)
{
if (item.IsStart)
{
result = await AddScheduleJobAsync(item);
if (result.Success)
{
Console.WriteLine($"QuartzNetJob{item.Name}启动成功!");
}
else
{
Console.WriteLine($"QuartzNetJob{item.Name}启动失败!错误信息:{result.Message}");
}
}
}
}
result.Message = $"初始化计划任务成功!";
}
catch (Exception ex)
{
result.Message = $"初始化计划任务失败:【{ex.Message}】";
}
return result;
}
#endregion
}
}

@ -3,11 +3,14 @@
<Import Project="..\build\common.targets" />
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Proxies" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
<PackageReference Include="Quartz" Version="3.7.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Tiobon.Core.Common\Tiobon.Core.Common.csproj" />
<ProjectReference Include="..\Tiobon.Core.DataAccess\Tiobon.Core.DataAccess.csproj" />
<ProjectReference Include="..\Tiobon.Core.IServices\Tiobon.Core.IServices.csproj" />
<ProjectReference Include="..\Tiobon.Core.Repository\Tiobon.Core.Repository.csproj" />
</ItemGroup>

@ -68,6 +68,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tiobon.Core.OPS.Tool", "Tio
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tiobon.Core.PublishHelper", "Tiobon.Core.PublishHelper\Tiobon.Core.PublishHelper.csproj", "{9B5E9966-1B4E-427E-838F-4AF0B742BE6C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tiobon.Core.Jobs", "Tiobon.Core.Jobs\Tiobon.Core.Jobs.csproj", "{CF66C4DE-8E0C-4FAD-901A-2B7E1E485ABA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -150,6 +152,10 @@ Global
{9B5E9966-1B4E-427E-838F-4AF0B742BE6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9B5E9966-1B4E-427E-838F-4AF0B742BE6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9B5E9966-1B4E-427E-838F-4AF0B742BE6C}.Release|Any CPU.Build.0 = Release|Any CPU
{CF66C4DE-8E0C-4FAD-901A-2B7E1E485ABA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF66C4DE-8E0C-4FAD-901A-2B7E1E485ABA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF66C4DE-8E0C-4FAD-901A-2B7E1E485ABA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF66C4DE-8E0C-4FAD-901A-2B7E1E485ABA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save