使用 Azure 中的 Web 应用程序使用多个部署使 Webjob 成为单例

Making a Webjob a singleton using multiple deployments using Web Apps in Azure

使用 Azure WebApps 我知道我可以通过将 "is_singleton": true 添加到 WebJob settings.job 文件来使 WebJob 成为单例,例如,如果我有 3 个实例,这会很好用WebApp 部署。

但是 - 我怎样才能发布到两个 WebApp(用例,两个不同的区域)并使 WebJob 运行 成为单例并且仅在其中一个部署上。


所需行为示例:

悉尼部署

新加坡部署


我知道我可以登录到 Azure 门户并在其中一个部署中禁用 Web 作业,但是我是否可以对 visual studio 中的发布配置文件进行转换或更改以实现所需的自动行为?

我目前正在使用 Visual Studio 2015 进行部署。

从站点的角度来看,那是两个完全独立的站点,因此其中的webjobs将相互独立。如果你想让它们成为单例,你必须添加一些自定义逻辑。

选项包括:

  1. 在两个站点之一中设置应用程序设置,并告诉网络作业仅在设置了该设置后才执行
  2. 使用 Azure blob 存储创建一个锁文件,获得锁的 webjob 是唯一可以运行(这让您的 webjob 故障转移到第二个区域,第一个失败)

实际上有一个非常方便的 Singleton 属性可能对您的用例有用,take a look at this,摘录如下;

The WebJobs SDK facilitates common distributed locking scenarios via its SingletonAttribute. You can simply apply SingletonAttribute to a job function to ensure that all invocations of that function will be serialized, even across scaled out instances.

[Singleton]
public static async Task ProcessImage([BlobTrigger("images")] Stream image)
{
     // Process the image
}

还有一个示例说明如何将 Singleton 缩小到一个区域:

You can specify a scope expression/value on the Singleton which will ensure that all executions of the function at that scope will be serialized.

[Singleton("{Region}")]
public static async Task ProcessWorkItem([QueueTrigger("workitems")] WorkItem workItem)
{
     // Process the work item
}