我想将Hangfire服务器处理的作业限制为一组列入白名单的方法或类。例如,如果客户端A将使用非白名单方法的Hangfire作业排队,则服务器B不应执行该作业。
我考虑过为此目的使用作业过滤器
class AllowedJobFilter : JobFilterAttribute
{
var getMethodInfo(Action a)
{
return a.Method;
}
void OnPerforming(PerformingContext context) {
// Only allow jobs which run Console.WriteLine()
var allowedMethods = new List<MethodInfo>() {
getMethodInfo(Console.WriteLine),
};
if (!allowedMethods.Contains(context.BackgroundJob.Job.Method)
{
throw Exception("Method is not allowed");
}
}
...
GlobalConfiguration.Configuration
.UseFilter(new AllowedJobFilter())
我不确定这种方法是否会按预期工作(因为没有任何内容表明Hangfire无法捕获和忽略JobFilterAttribute中的异常),并且这种方法会使工作失败而不是跳过它,这可能不是所希望的。有没有更好的方法来限制哪些作业可以在服务器上运行?
答案 0 :(得分:0)
根据我提交的有关Github问题的回复:
https://github.com/HangfireIO/Hangfire/issues/1403
burningice2866评论14天前
您可以在JobFilter中实现OnCreating方法,并将context.Canceled设置为true。如您所见,使用这种方法可以在创建过程中忽略作业。
Hangfire/src/Hangfire.Core/Client/BackgroundJobFactory.cs
Line 112 in 23d81f5
if (preContext.Canceled)
{
return new CreatedContext(preContext, null, true, null);
}
@ burningice2866 贡献者 burningice2866 14天前评论了
您还应该能够按照此处所述在OnPerforming中设置“已取消”
Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs
Line 147 in 23d81f5
if (preContext.Canceled)
{
return new PerformedContext(
preContext, null, true, null);
}