Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學

Windows Azure 常見問題與解決方案 (下):PartitionKey/RowKey 設計、HttpHandler 設定、Storage 連線字串初始化

編輯:Win7 系統基礎知識

前言

承接上集 Azure Table Service 效能調優,本文解決三大開發實戰問題:PartitionKey/RowKey 設計原則、Web Role 中自訂 HttpHandler 正確設定、Role 設定檔 Storage 連線字串初始化錯誤修復。

1.4 合理設計 PartitionKey & RowKey

Azure 表格儲存以 PartitionKey + RowKey 複合主鍵分散資料。設計原則:

  • 查詢模式驅動設計:最常用查詢條件作 PartitionKey,第二常用作 RowKey
  • 熱分區避免:避免單一 PartitionKey 承載過多寫入 (如全部用 DateTime.Now.Ticks 導致寫入集中最新分區)
  • 範圍查詢支援:RowKey 設計為可排序字串 (如反轉時間戳 string.Format("{0:D19}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks)) 支援時間範圍掃描
  • 實體群組交易 (EGT):同一 PartitionKey 內最多 100 筆、4MB 可原子批次操作

參考:More about PartitionKey & RowKey

2. Web Role 中使用自訂 HttpHandler (IIS 7 整合管線模式)

錯誤示範 (傳統模式設定)

<system.web>
  <httpHandlers>
    <add verb="*" path="*.do" type="MyHandler" />
  </httpHandlers>
</system.web>

部署至 Azure Web Role (IIS 7+ 整合模式) 會報錯:HTTP 500.21 - Handler not found in integrated pipeline

正確設定 (system.webServer/handlers)

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" />
  <validation validateIntegratedModeConfiguration="false" />
  <handlers>
    <add name="KeywordsHandler" path="*.do" verb="GET" 
         type="KeywordsWebRole.KeywordsHandler, KeyWordsWebRole" 
         resourceType="Unspecified" allowPathInfo="true" />
  </handlers>
</system.webServer>

關鍵點:system.webServer/handlers、runAllManagedModulesForAllRequests="true"、validateIntegratedModeConfiguration="false"

3. Role 設定檔 Storage 連線字串初始化 CloudStorageAccount

錯誤代碼

CloudStorageAccount account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
// Exception: SetConfigurationSettingPublisher needs to be called before FromConfigurationSetting can be used.

修正方案:在 WebRole/WorkerRole OnStart() 中設定 Publisher

public override bool OnStart()
{
    CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
    {
        configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
        RoleEnvironment.Changed += (sender, arg) =>
        {
            if (arg.Changes.OfType<RoleEnvironmentConfigurationSettingChange>()
                .Any(change => change.ConfigurationSettingName == configName))
            {
                if (!configSetter(RoleEnvironment.GetConfigurationSettingValue(configName)))
                {
                    RoleEnvironment.RequestRecycle();
                }
            }
        };
    });
    return base.OnStart();
}

原理:Azure SDK 1.3+ 要求發布者模式 讀取組態設定,支援執行時動態變更不重啟角色。

結語

Azure 開發三大實戰坑:PartitionKey/RowKey 設計決定查詢效能與成本、IIS 7 整合管線強制 system.webServer/handlers、組態讀取需發布者模式。掌握這三點,避開 80% 部署與效能問題。Azure 平台專業性極強,建議配合官方最佳實踐文檔與 SDK 更新持續學習。

Copyright © Windows教程網 All Rights Reserved