问题
In case of Cloud Service in Azure (maybe also App Service), how can I run some code before the service become available in swap or in case of new instance.
for example, loading data to cache before the first user have access.
回答1:
Cloud Services with Roles
Place your app init code inside OnStart()
.
From https://msdn.microsoft.com/library/azure/microsoft.windowsazure.serviceruntime.roleentrypoint.onstart.aspx:
public class WorkerRole : RoleEntryPoint
{
public override bool OnStart()
{
try
{
// Add initialization code here
}
catch (Exception e)
{
Trace.WriteLine("Exception during OnStart: " + e.ToString());
// Take other action as needed.
}
return base.OnStart();
}
}
Before the
OnStart
method returns, the status of the role instance is set to Busy and the instance is not available through the load balancer.If the
OnStart
method returns false, the role instance is immediately stopped. If the method returns true, Windows Azure starts the role by calling the Run method. In general, you should avoid returning false from theOnStart
method.
App Service
Use the Application Initialization IIS module. The mechanism is described in detail here - http://ruslany.net/2015/09/how-to-warm-up-azure-web-app-during-deployment-slots-swap/
web.config:
<system.webServer>
<applicationInitialization >
<add initializationPage="/warmup-cache.php" hostName="site.azurewebsites.net"/>
</applicationInitialization>
<system.webServer>
来源:https://stackoverflow.com/questions/39943566/azure-app-or-cloud-service-run-some-code-before-load-balncer