我在托管服务中具有辅助角色。 工作人员每天都会发送电子邮件。 但在托管服务中,有 2 个环境:Staging 和 Production。 所以我的 worker 角色每天发送电子邮件 2 次。 我想知道如何检测 worker 是否处于停滞状态或生产状态。 提前致谢。
最佳答案
根据我的问题here ,您会发现没有快速的方法可以做到这一点。另外,除非您真的知道自己在做什么,否则我强烈建议您不要这样做。
但是,如果您愿意,您可以使用一个非常好的库(Azure Service Management via C#),尽管我们确实有一些trouble with WCF using it.
以下是有关如何执行此操作的快速示例(请注意,您需要将管理证书作为资源包含在代码中并将其部署到 Azure):
private static bool IsStaging()
{
try
{
if (!CloudEnvironment.IsAvailable)
return false;
const string certName = "AzureManagement.pfx";
const string password = "Pa$$w0rd";
// load certificate
var manifestResourceStream = typeof(ProjectContext).Assembly.GetManifestResourceStream(certName);
if (manifestResourceStream == null)
{
// should we panic?
return true;
}
var bytes = new byte[manifestResourceStream.Length];
manifestResourceStream.Read(bytes, 0, bytes.Length);
var cert = new X509Certificate2(bytes, password);
var serviceManagementChannel = Microsoft.Toolkit.WindowsAzure.ServiceManagement.ServiceManagementHelper.
CreateServiceManagementChannel("WindowsAzureServiceManagement", cert);
using (new OperationContextScope((IContextChannel)serviceManagementChannel))
{
var hostedServices =
serviceManagementChannel.ListHostedServices(WellKnownConfiguration.General.SubscriptionId);
// because we don't know the name of the hosted service, we'll do something really wasteful
// and iterate
foreach (var hostedService in hostedServices)
{
var ad =
serviceManagementChannel.GetHostedServiceWithDetails(
WellKnownConfiguration.General.SubscriptionId,
hostedService.ServiceName, true);
var deployment =
ad.Deployments.Where(
x => x.PrivateID == Zebra.Framework.Azure.CloudEnvironment.CurrentRoleInstanceId).
FirstOrDefault
();
if (deployment != null)
{
return deployment.DeploymentSlot.ToLower().Equals("staging");
}
}
}
return false;
}
catch (Exception e)
{
// if something went wrong, let's not panic
TraceManager.AzureFrameworkTraceSource.TraceData(System.Diagnostics.TraceEventType.Error, "Exception", e);
return false;
}
}
关于azure - 如何检测环境是在 Azure 托管服务 worker 角色中进行暂存还是生产?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7391284/