Azure 应用程序或云服务,运行 负载均衡器之前的一些代码

Azure app or cloud service, run some code before load balncer

如果是 Azure 中的云服务(也可能是 App 服务),我如何 运行 在服务在交换或新实例的情况下变得可用之前编写一些代码。

例如,在第一个用户访问之前将数据加载到缓存。

具有角色的云服务

将您的应用初始化代码放在 OnStart().

来自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 the OnStart method.

应用服务

使用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>