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

重要

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

web.config ファイルのManaged Cache Service設定は、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, "mycache.cache.windows.net");
    
  3. s プロパティを config.SecurityPropertie新しい 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");