如何限制Hangfire Server中允许的方法

问题描述 投票:1回答:1

我想限制Hangfire服务器处理哪些作业到某组白名单方法或类。例如,如果客户端A对使用非白名单方法的Hangfire作业进行排队,则服务器B不应该执行它。

我想过为此目的使用Job Filter

    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的异常),并且这种方法将失败而不是跳过它,这可能是不可取的。有没有更好的方法来限制哪些作业可以在服务器上运行?

hangfire
1个回答
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 Contributor burningice2866于14天前评论过

您应该能够在此处所述的OnPerforming中设置已取消

Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs

Line 147 in 23d81f5

 if (preContext.Canceled)
 {
         return new PerformedContext(
             preContext, null, true, null);
 }

© www.soinside.com 2019 - 2024. All rights reserved.