共用方式為


如何:在 Azure 受控快取服務 的 RoleEntryPoint 方法中建立 DataCache 物件

重要

Microsoft 建議使用 Azure Redis 快取的所有新開發。 如需選擇 Azure 快取供應專案的目前檔和指引,請參閱 哪一個 Azure 快取供應專案適合我?

web.config檔案中的受控快取服務設定不會自動從RoleEntryPoint類別的內容取得, (通常定義于 WebRole.cs 檔案) 中。 當您嘗試在RoleEntryPoint類別方法中建立DataCache物件時,會發生下列錯誤:

{"ErrorCode<ERRCA0021>:SubStatus<ES0001>:Server collection cannot be empty."}

這是因為web.config檔案中的 dataCacheClient 設定不會自動套用至新的 DataCache 用戶端物件。 具體而言, autoDiscover 元素的屬性無法使用,因此 DataCache 物件無法以裝載快取的角色為目標。

在此案例中,您必須以程式設計方式設定 DataCacheFactoryConfiguration 物件,以直接存取web.config檔案中的設定。

如何以程式設計方式設定快取用戶端

  1. 建立 DataCacheFactoryConfiguration 物件。

    DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();
    
  2. AutoDiscoveryProperty 設定為新的 DataCacheAutoDiscoverProperty 物件。 此屬性用來連線至快取。 指定 true 以啟用自動探索。 也會指定快取端點。

    config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "mycache.cache.windows.net");
    
  3. config.SecurityPropertie s 屬性設定為新的 DataCacheSecurity 實例,並指定快取的存取金鑰,以及是否要在快取和用戶端之間啟用 SSL 通訊。

    config.SecurityProperties = new DataCacheSecurity("[Replace with Access Key]", false);
    

    注意

    如需詳細資訊,請參閱 保護快取用戶端與快取之間的通訊

  4. 在控制快取用戶端行為的 DataCacheFactoryConfiguration 物件上設定任何其他屬性。

  5. 建立 DataCacheFactory 物件,並在建構函式中傳遞 DataCacheFactoryConfiguration 物件。

    DataCacheFactory factory = new DataCacheFactory(config);
    
  6. 呼叫 DataCacheFactory.GetCache 方法,以傳回目標具名快取的 DataCache 物件。

    DataCache cache = factory.GetCache("default");
    

範例

// Create a DataCacheFactoryConfiguration object
DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();

// Enable the AutoDiscoveryProperty (and any other required configuration settings):
config.AutoDiscoverProperty = 
    new DataCacheAutoDiscoverProperty(true, "mycache.cache.windows.net");

// Configure the access key and sslEnabled setting.
config.SecurityProperties = new DataCacheSecurity("[Replace with Access Key]", false);

// Create a DataCacheFactory object with the configuration settings:
DataCacheFactory factory = new DataCacheFactory(config);

// Use the factory to create a DataCache client for the "default" cache:
DataCache cache = factory.GetCache("default");