WTM框架使用技巧之:整合HangFire
快点关注我们吧
作者介绍
翁薪钧,现就职于华东院,前端开发。从事过winform,上位机开发,wms开发。疫情期间接触wtm框架,先后使用了layui,vue版本。使用wtm框架,主要是看重了代码生成器,权限分配,用户管理,数据库操作等功能。之前苦于没有一个好的框架,一直都是手写代码,效率低下,重复劳动。现在用wtm,crud基础的代码都是生成,自己专注于业务逻辑,效率提高,bug减少了很多。也是接触了wtm,自己也开始学习.net core,从.net core2.2一直到现在.net 5.0,跟着wtm一同进步了很多。
定时任务选用Hangfire主要是看中他自带面板功能。
在model引入 Hangfire Hangfire.SQLite
在startup.cs 文件
public void ConfigureServices(IServiceCollection services)
var sqliteOptions = new SQLiteStorageOptions();
SQLitePCL.Batteries.Init();
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseLogProvider(new ColouredConsoleLogProvider())
.UseSQLiteStorage("Data Source=./wg.db;", sqliteOptions) );
3.在 public void Configure(IApplicationBuilder app, IOptionsMonitor
var option = new BackgroundJobServerOptions {
WorkerCount = 1 };
app.UseHangfireServer(option);
app.UseDeveloperExceptionPage();
app.UseHangfireDashboard("/hangfire",
new Hangfire.DashboardOptions {
Authorization = new[] {
new MyDashboardAuthorizationFilter()
}
});
RecurringJob.AddOrUpdate<WeatherJobService>("获取天气数据", p => p.GetWeatherInfo(), Cron.Daily(8));
写 MyDashboardAuthorizationFilter
`
using Hangfire.Annotations;
using Hangfire.Dashboard;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace zoecloud.JobService
{
public class MyDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize([NotNull] DashboardContext context)
{
var httpContext = context.GetHttpContext();
var header = httpContext.Request.Headers["Authorization"];
if (string.IsNullOrWhiteSpace(header))
{
SetChallengeResponse(httpContext);
return false;
}
var authValues = System.Net.Http.Headers.AuthenticationHeaderValue.Parse(header);
if (!"Basic".Equals(authValues.Scheme, StringComparison.InvariantCultureIgnoreCase))
{
SetChallengeResponse(httpContext);
return false;
}
var parameter = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authValues.Parameter));
var parts = parameter.Split(':');
if (parts.Length < 2)
{
SetChallengeResponse(httpContext);
return false;
}
var username = parts[0];
var password = parts[1];
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
{
SetChallengeResponse(httpContext);
return false;
}
if (username == "admin" && password == "123456")
{
return true;
}
SetChallengeResponse(httpContext);
return false;
}
private void SetChallengeResponse(HttpContext httpContext)
{
httpContext.Response.StatusCode = 401;
httpContext.Response.Headers.Append("WWW-Authenticate", "Basic realm=\\"Hangfire Dashboard\\"");
httpContext.Response.WriteAsync("Authentication is required.");
}
}
}
`
写自己的服务
`
public class WeatherJobService
{
CS connection;
Logger logger;
ILedServer ledServer;
public WeatherJobService(IServiceScopeFactory serviceScopeFactory)
{
logger = LogManager.GetCurrentClassLogger();
var wtmContext = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService<WTMContext>();
connection = wtmContext.ConfigInfo.Connections[0];
ledServer = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService<ILedServer>();
}
//[Hangfire.Queue("get_weather")]
public void GetWeatherInfo()
{
try
{
using (var udc = connection.CreateDC())
{
var restclient = new RestClient("http://wthrcdn.etouch.cn/WeatherApi");
var orgList = udc.Set<Organization>().ToList();
for (int i = 0; i < orgList.Count; i++)
{
if (!string.IsNullOrEmpty(orgList[i].WeatherCity))
{
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
request.Timeout = 5000;
request.AddParameter("city", orgList[i].WeatherCity);
var response = restclient.Execute(request);
var content = response.Content;
logger.Info($"组织名称,{orgList[i].Name},{content}");
orgList[i].StrWeather = JsonConvert.SerializeObject(XmlHelper.XmlDeSeralizer<resp>(content));
udc.Set<Organization>().Update(orgList[i]);
}
}
udc.SaveChanges();
ledServer.SendWeatherInfo(null);
}
}
catch (Exception ex)
{
logger.Info(ex.Message);
}
}
}`
调用自己的服务
后端面板链接
xxx:端口/hangfire
面板可以手动触发自己写的定时任务,可以把面板作为外部链接添加到wtm菜单里面
HangFire官网文档链接
https://www.hangfire.io/
- 本文分类:技术
- 本文标签:无
- 浏览次数:304 次浏览
- 发布日期:2021-09-08 20:46:44
- 本文链接:http://muker.cc/cms/tech2/317.html
- 上一篇 > 开源版“微信”,比原版更牛批!
- 下一篇 > .NET Core 基于Quartz的UI可视化操作组件
发表评论 取消回复