1. 程式人生 > 其它 >【Azure 應用服務】在Azure App Service多例項的情況下,如何在應用中通過程式碼獲取到例項名(Instance ID)呢?

【Azure 應用服務】在Azure App Service多例項的情況下,如何在應用中通過程式碼獲取到例項名(Instance ID)呢?

問題描述

App Service開啟多例項後,如何在程式碼中獲取當前請求所真實達到的例項呢?

問題答案

App Service為通過環境變數的方式來顯示輸出例項ID等資訊,如:

Website Environment Variables

  • WEBSITE_SITE_NAME- The name of the site.
  • WEBSITE_SKU- The sku of the site (Possible values:Free,Shared,Basic,Standard).
  • WEBSITE_COMPUTE_MODE- Specifies whether website is on adedicatedorsharedVM/s (Possible values:Shared
    ,Dedicated).
  • WEBSITE_HOSTNAME- The Azure Website's primary host name for the site (For example:site.azurewebsites.net). Note that custom hostnames are not accounted for here.
  • WEBSITE_INSTANCE_ID- The id representing the VM that the site is running on (If site runs on multiple instances, each instance will have a different id).
  • WEBSITE_NODE_DEFAULT_VERSION- The default node version this website is using.
  • WEBSOCKET_CONCURRENT_REQUEST_LIMIT- The limit for websocket's concurrent requests.
  • WEBSITE_COUNTERS_ALL- (Windows only) all perf counters (ASPNET, APP and CLR) in JSON format. You can access specific one such as ASPNET byWEBSITE_COUNTERS_ASPNET
    .

可以通過App Service的高階管理工具(Kudu站點)來檢視這些資訊:

所以如果要在程式碼中獲取Instance ID資訊,可以直接通過var instanceID = Configuration["WEBSITE_INSTANCE_ID"] 獲取。全部例項程式碼為:

Index.cshtml.cs :

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace MyFirstAzureWebApp.Pages;

public class IndexModel : PageModel
{
    private readonly IConfiguration Configuration;
 
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
    {
        _logger = logger;
        Configuration = configuration;
    }

    public void OnGet()
    {
        var instanceID = Configuration["WEBSITE_INSTANCE_ID"];

        ViewData["InstanceID"] = instanceID;

        //return Content($"Instance ID value: {instanceID} \n");
    }
}

如要快速建立一個ASP.NET應用來驗證Instance ID,可以參考文件:https://docs.azure.cn/zh-cn/app-service/quickstart-dotnetcore?tabs=net60#create-an-aspnet-web-app

Index.cshtml 檔案內容為:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<div class="text-center">
    <h1 class="display-4">Welcome</h1>
     <div>
        The current Instance ID is:@ViewData["InstanceID"];
    </div>
    <hr />
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
   
</div>

釋出到App Service後,就可以檢驗效果:

此外,如果App Service開啟了ARR Affinity(請求粘連性)功能後,在客戶端的Cookie值ARRAffinity和ARRAffinitySameSite中,也是可以找到Instance ID資訊。如:

參考資料

Azure runtime environmenthttps://github.com/projectkudu/kudu/wiki/Azure-runtime-environment#website-environment-variables

快速入門:部署 ASP.NET Web 應用https://docs.azure.cn/zh-cn/app-service/quickstart-dotnetcore?tabs=net60#create-an-aspnet-web-app

當在複雜的環境中面臨問題,格物之道需:濁而靜之徐清,安以動之徐生。 雲中,恰是如此!