Azure Web 角色和实例

Azure Web Roles and Instances

我有一个具有 多个实例 的 Web 角色。我想每天早上 7 点通过电子邮件向我的客户发送他们的统计数据。 我的问题如下:如果我使用 Cron 作业 来完成工作,邮件将被发送多次

如何配置我的实例以便只向我的每个客户发送一封电子邮件?

通常,使用 Multi-instance Cloud Services 解决此问题的方法是使用 Master Election 模式。您要做的是在 7:00 AM(或每当您的 CRON 作业启动时),您的所有实例都将尝试获取 blob 上的租约。但是,只有一个实例会成功获取租约,而其他实例将失败并出现 PreConditionFailed (419) 错误(确保捕获此异常!)。获取租约的实例本质上是一个 Master 并且该实例将发送电子邮件。

显然,这种方法的问题在于,如果此 Master 实例无法传递消息怎么办。但我想那是另一个问题 :).

根据我的经验,我认为您可以尝试使用唯一的实例 ID 来确保有一个实例可以作为 cron 作业发送电子邮件。

这是一个简单的代码。

import com.microsoft.windowsazure.serviceruntime.RoleEnvironment;

String instanceId = RoleEnvironment.getCurrentRoleInstance().getId();
if("<instace-id-for-running-cronjob>".equals(instanceId)) {
    // Coding for cron job
    .....
}

作为参考,请参阅下面的功能说明RoleInstance.getId

Returns the ID of this instance.
The returned ID is unique to the application domain of the role's instance. If an instance is terminated and has been configured to restart automatically, the restarted instance will have the same ID as the terminated instance.

有关在 Java 的 Azure SDK 中使用上述 class 的更多详细信息,请参阅下面的 classes 列表。

希望对您有所帮助。