Skip to content

Commit

Permalink
集成定时任务Quartz,更新文件:数据库表(db文件夹中找)Sys_QuartzLog、Sys_QuartzOptions同时将两张表正…
Browse files Browse the repository at this point in the history
…常生成代码(生成代码时类库选择system,文件夹输入Quartz) ;后台vol.core类型下Filters、Quartz文件夹、Startup.cs、system类库下Quartz文件夹;VOL.WebApi类库下System->Partial文件夹下Sys_QuartzOptions.cs文件;前端:extension->system文件夹下quartz;页面菜单->下拉框绑定设置中添加数据字典:参照现有字典配置:请求方式
  • Loading branch information
283591387@qq.com committed Sep 6, 2022
1 parent 2de819c commit ae5a2d7
Show file tree
Hide file tree
Showing 122 changed files with 24,532 additions and 750 deletions.
10 changes: 9 additions & 1 deletion .Net6版本/VOL.Core/Filters/ApiAuthorizeFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using VOL.Core.Configuration;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using static VOL.Core.Filters.ApiTaskAttribute;

namespace VOL.Core.Filters
{
Expand All @@ -31,8 +32,15 @@ public void OnAuthorization(AuthorizationFilterContext context)
//if (context.Filters.Any(item => item is IAllowAnonymousFilter))
if (context.ActionDescriptor.EndpointMetadata.Any(item => item is IAllowAnonymous))
{
//如果使用了固定Token不过期,直接对token的合法性及token是否存在进行验证
if (context.Filters
.Where(item => item is IApiTaskFilter)
.FirstOrDefault() is IApiTaskFilter apiTaskFilter)
{
apiTaskFilter.OnAuthorization(context);
return;
}
//如果使用了固定Token不过期,直接对token的合法性及token是否存在进行验证
else if (context.Filters
.Where(item => item is IFixedTokenFilter)
.FirstOrDefault() is IFixedTokenFilter tokenFilter)
{
Expand Down
26 changes: 26 additions & 0 deletions .Net6版本/VOL.Core/Filters/ApiTaskAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Text;
using VOL.Core.Configuration;
using VOL.Core.Extensions;
using VOL.Core.Quartz;

namespace VOL.Core.Filters
{
public interface IApiTaskFilter : IFilterMetadata
{
AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context);
}
public class ApiTaskAttribute : Attribute, IApiTaskFilter, IAllowAnonymous
{
public AuthorizationFilterContext OnAuthorization(AuthorizationFilterContext context)
{
return QuartzAuthorization.Validation(context) ;
}
}

}
54 changes: 54 additions & 0 deletions .Net6版本/VOL.Core/Quartz/HttpManager.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace VOL.Core.Quartz
{
public static class HttpManager
{

public static async Task<string> SendAsync(this IHttpClientFactory httpClientFactory,
HttpMethod method,
string url,
string postData=null,
int timeOut=180,
Dictionary<string, string> headers = null)
{
var client = httpClientFactory.CreateClient();
var content = new StringContent(postData??"");
var request = new HttpRequestMessage(method, url)
{
Content = content
};
headers ??= new Dictionary<string, string>();
headers.TryAdd(QuartzAuthorization.Key, QuartzAuthorization.AccessKey);
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Add(header.Key, header.Value);
}
}
try
{
client.Timeout = TimeSpan.FromSeconds(timeOut);
HttpResponseMessage httpResponseMessage = await client.SendAsync(request);
var result = await httpResponseMessage.Content
.ReadAsStringAsync();
return result;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
QuartzFileHelper.Error($"http请求异常,url:{url},{ex.Message+ex.StackTrace}");
return ex.Message;
}
}
}
}
134 changes: 134 additions & 0 deletions .Net6版本/VOL.Core/Quartz/HttpResultfulJob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using VOL.Core.Configuration;
using VOL.Core.EFDbContext;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;

namespace VOL.Core.Quartz
{
public class HttpResultfulJob : IJob
{
readonly IHttpClientFactory _httpClientFactory;

readonly IServiceProvider _serviceProvider;
/// <summary>
/// 2020.05.31增加构造方法
/// </summary>
/// <param name="serviceProvider"></param>
/// <param name="httpClientFactory"></param>
public HttpResultfulJob(IServiceProvider serviceProvider, IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
_serviceProvider = serviceProvider;
}
public async Task Execute(IJobExecutionContext context)
{
DateTime dateTime = DateTime.Now;
Sys_QuartzOptions taskOptions = context.GetTaskOptions();
string httpMessage = "";
AbstractTrigger trigger = (context as JobExecutionContextImpl).Trigger as AbstractTrigger;
if (taskOptions == null)
{
Console.WriteLine($"未获取到作业");
return;
}
if (string.IsNullOrEmpty(taskOptions.ApiUrl) || taskOptions.ApiUrl == "/")
{
Console.WriteLine($"未配置作业:{taskOptions.TaskName}的url地址");
QuartzFileHelper.Error($"未配置作业:{taskOptions.TaskName}的url地址");
return;
}
string exceptionMsg = null;

try
{
using (var dbContext = new VOLContext())
{
var _taskOptions = dbContext.Set<Sys_QuartzOptions>().AsTracking()
.Where(x => x.Id == taskOptions.Id).FirstOrDefault();

if (_taskOptions != null)
{
_taskOptions.LastRunTime = DateTime.Now;
dbContext.Update(_taskOptions);
var entry = dbContext.Entry(_taskOptions);
entry.State = EntityState.Unchanged;
entry.Property("LastRunTime").IsModified = true;
dbContext.SaveChanges();
}
}

Dictionary<string, string> header = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(taskOptions.AuthKey)
&& !string.IsNullOrEmpty(taskOptions.AuthValue))
{
header.Add(taskOptions.AuthKey.Trim(), taskOptions.AuthValue.Trim());
}

httpMessage = await _httpClientFactory.SendAsync(
taskOptions.Method?.ToLower() == "get" ? HttpMethod.Get : HttpMethod.Post,
taskOptions.ApiUrl,
taskOptions.PostData,
taskOptions.TimeOut ?? 180,
header); ;
}
catch (Exception ex)
{
exceptionMsg = ex.Message + ex.StackTrace;
}
finally
{
try
{
var log = new Sys_QuartzLog
{
LogId = Guid.NewGuid(),
TaskName = taskOptions.TaskName,
Id = taskOptions.Id,
CreateDate = dateTime,
ElapsedTime = Convert.ToInt32((DateTime.Now - dateTime).TotalSeconds),
ResponseContent = httpMessage,
ErrorMsg = exceptionMsg,
StratDate = dateTime,
Result = exceptionMsg == null ? 1 : 0,
EndDate = DateTime.Now
};
using (var dbContext = new VOLContext())
{
dbContext.Set<Sys_QuartzLog>().Add(log);
dbContext.SaveChanges();
}
}
catch (Exception ex)
{
Console.WriteLine($"日志写入异常:{taskOptions.TaskName},{ex.Message}");
QuartzFileHelper.Error($"日志写入异常:{typeof(HttpResultfulJob).Name},{taskOptions.TaskName},{ex.Message}");
}
}
Console.WriteLine(trigger.FullName + " " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss") + " " + httpMessage);
return;
}
}
public class TaskOptions
{
public string TaskName { get; set; }
public string GroupName { get; set; }
public string Interval { get; set; }
public string ApiUrl { get; set; }
public string AuthKey { get; set; }
public string AuthValue { get; set; }
public string Describe { get; set; }
public string RequestType { get; set; }
public DateTime? LastRunTime { get; set; }
public int Status { get; set; }
}
}
28 changes: 28 additions & 0 deletions .Net6版本/VOL.Core/Quartz/IOCJobFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VOL.Core.Quartz
{
public class IOCJobFactory: IJobFactory
{
private readonly IServiceProvider _serviceProvider;
public IOCJobFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return _serviceProvider.GetService(bundle.JobDetail.JobType) as IJob;

}

public void ReturnJob(IJob job)
{
(job as IDisposable)?.Dispose();
}
}
}
17 changes: 17 additions & 0 deletions .Net6版本/VOL.Core/Quartz/JobAction.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;

namespace VOL.Core.Quartz
{
public enum JobAction
{
新增 = 1,
删除 = 2,
修改 = 3,
暂停 = 4,
停止,
开启,
立即执行
}
}
71 changes: 71 additions & 0 deletions .Net6版本/VOL.Core/Quartz/QuartzAuthorization.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using VOL.Core.Configuration;
using VOL.Core.Extensions;

namespace VOL.Core.Quartz
{
public static class QuartzAuthorization
{

private static string _quartzAccessKey;

public static string Key = "QuartzAccessKey";
public static string AccessKey
{
get
{
if (string.IsNullOrEmpty(_quartzAccessKey))
{
_quartzAccessKey = GetAccessKey();
}
return _quartzAccessKey;
}
}
public static string GetAccessKey()
{
if (string.IsNullOrEmpty(_quartzAccessKey))
{
_quartzAccessKey = AppSetting.GetSettingString(Key);
}
if (string.IsNullOrEmpty(_quartzAccessKey))
{
_quartzAccessKey = Guid.NewGuid().ToString();
}
using (MD5 md5 = MD5.Create())
{
string md5str = _quartzAccessKey;
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(AppSetting.Secret.User));
for (int i = 0; i < s.Length; i++)
{
string btos = s[i].ToString("X2");
md5str += btos;
}
return md5str;
}
}

public static AuthorizationFilterContext Validation(AuthorizationFilterContext context)
{
if (context.HttpContext.Request.Headers.TryGetValue(Key, out StringValues value))
{
if (AccessKey != value)
{
context.Result = new ContentResult()
{
Content = new { message = "key不匹配", status = false, code = 401 }.Serialize(),
ContentType = "application/json",
StatusCode = 401
};
return context;
}
}
return context;
}
}
}
36 changes: 36 additions & 0 deletions .Net6版本/VOL.Core/Quartz/QuartzFileHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Text;
using VOL.Core.Configuration;
using VOL.Core.Extensions;
using VOL.Core.Utilities;

namespace VOL.Core.Quartz
{
public static class QuartzFileHelper
{
public static void OK(string message)
{
Write(message, "log");
}

public static void Error(string message)
{
Write(message, "error");
}

private static void Write(string message,string folder)
{
try
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd");
string path = $"{AppSetting.CurrentPath}\\quartz\\{folder}\\".ReplacePath();
FileHelper.WriteFile(path, $"{fileName}.txt", message, true);
}
catch (Exception ex)
{
Console.WriteLine($"文件写入异常{message},{ex.Message + ex.StackTrace}");
}
}
}
}
Loading

0 comments on commit ae5a2d7

Please sign in to comment.