hangfire - 如何限制 Hangfire Server 中允许的方法
问题描述
我想将 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 的异常),并且这种方法会使工作失败而不是跳过它,这可能是不可取的。有没有更好的方法来限制哪些作业可以在服务器上运行?
解决方案
根据我提交的关于 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 中设置 Canceled ,如此处所述
Hangfire/src/Hangfire.Core/Server/BackgroundJobPerformer.cs
Line 147 in 23d81f5
if (preContext.Canceled)
{
return new PerformedContext(
preContext, null, true, null);
}
推荐阅读
- java - Spring MVC @RequestBody 不适用于 JSONObject
- reactjs - React Redux,仅在第一页加载时从 API 加载数据。加载数据后渲染组件
- kubernetes - 在单节点集群的情况下,主节点和工作节点是同一个节点吗?
- python - python - 美丽的汤链接解析不起作用
- java - 从通用数组列表中查找最大值
- javascript - 如何关闭由结帐脚本打开的弹出窗口
- javascript - 我可以从 Realm React Native 中的嵌套对象架构上的关系方法访问具有循环引用的属性对象吗
- cpu-architecture - 用于可忽略负载的 Risc-V 扩展
- python - Python 数据框的堆积面积图
- php - 在 PHP 中使用简单的 html dom 抓取数据奇数属性