Share via


方法: Azure In-Role Cache の RoleEntryPoint メソッドで DataCache オブジェクトを作成する

重要

Microsoft では、すべての新しい開発で Azure Redis Cache を使用することをお勧めします。 Azure Cache オファリングの選択に関する最新のドキュメントとガイダンスについては、自分に適した Azure Cache オファリングを参照してください。

Microsoft Azure web.config ファイルのキャッシュ設定は、RoleEntryPoint クラス (通常は WebRole.cs ファイルで定義) のコンテキストから自動的には使用できません。 RoleEntryPoint クラス メソッドで DataCache オブジェクトを作成しようとすると、次のエラーが発生します。

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

これは、web.config ファイルの dataCacheClient 設定が新しい DataCache クライアント オブジェクトに自動的に適用されないために発生します。 具体的には、 autoDiscover 要素の属性は使用できないため、 DataCache オブジェクトはキャッシュをホストするロールをターゲットにできません。

このシナリオでは、web.config ファイル内の設定に直接アクセスする DataCacheFactoryConfiguration オブジェクトをプログラムで構成する必要があります。

プログラムを使ってキャッシュ クライアントを構成する方法

  1. DataCacheFactoryConfiguration オブジェクトを作成します。

    DataCacheFactoryConfiguration config = new DataCacheFactoryConfiguration();
    
  2. AutoDiscoveryProperty を新しい DataCacheAutoDiscoverProperty オブジェクトに設定します。 自動検出を有効にするように true を指定します。 また、キャッシュをホストするロールの名前も指定します。

    config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "WebRole1");
    
  3. キャッシュ クライアントの動作を制御する DataCacheFactoryConfiguration オブジェクトに他のプロパティを設定します。

  4. DataCacheFactory オブジェクトを作成し、コンストラクターで DataCacheFactoryConfiguration オブジェクトを渡します。

    DataCacheFactory factory = new DataCacheFactory(config);
    
  5. DataCacheFactory.GetCache メソッドを呼び出して、ターゲットの名前付きキャッシュの DataCache オブジェクトを返します。

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

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

// Enable the AutoDiscorveryProperty (and any other required configuration settings):
config.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "WebRole1");

// 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");

参照

概念

Azure In-Role Cache 用の開発の概要