共用方式為


如何:搭配 Azure 受控快取服務使用自訂序列化程式

重要

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

Microsoft Azure快取會先序列化物件,再將它們放入快取中,然後還原序列化從快取擷取的物件。 在內部,序列化是由 NetDataContractSerializer 類別處理。 本主題說明如何建立和使用自訂序列化類別,以用於使用受控快取服務的 Azure 應用程式。

提示

您或許可以透過將已知類型的序列化最佳化,來增加效能優勢。 如需使用 受控快取服務 進行序列化的詳細資訊,請參閱Azure 受控快取服務的序列化

建立自訂序列化類別

  1. 請先準備快取用戶端以使用 受控快取服務。

  2. 建立衍生自 IDataCacheObjectSerializer 的類別。

  3. 在此介面中實作兩種方法: SerializeDeserialize

class MySerializer : IDataCacheObjectSerializer
{
    public object Deserialize(System.IO.Stream stream)
    {
            object returnObject = null;

            // Deserialize the System.IO.Stream 'stream' from
            // the cache and return the object.

            return returnObject;
    }

    public void Serialize(System.IO.Stream stream, object value)
    {
        // Serialize the object 'value' into the System.IO.Stream 'stream'
        // which will then be stored in the cache.
    }
}

使用組態檔指定自訂序列化程式

  1. 將自訂序列化程式的程式碼新增至專案,或新增實作自訂序列化程式之組件的參照。

  2. 在應用程式組態檔中,在dataCacheClient區段中新增serializationProperties元素。

  3. serializationProperties 元素內,將 序列化程式 屬性指派給 「CustomSerializer」。 將 customSerializerType 屬性指派給實作序列化程式的類別。

下列範例示範如何使用應用程式組態檔指定名稱為 MyNamespace.MySerializer 的自訂序列化程式。

<dataCacheClient>
    <serializationProperties serializer="CustomSerializer" 
       customSerializerType="MyNamespace.MySerializer, MyNamespace" />
    <!-- Other dataCacheClient settings omitted for clarity -->
</dataCacheClient>

使用程式碼指定自訂序列化程式

  1. 將自訂序列化程式的程式碼新增至專案,或新增實作自訂序列化程式之組件的參照。

  2. 使用建構函式指定DataCacheObjectSerializerType.CustomSerializer選項和序列化程式類別的新實例,建立DataCacheSerializationProperties物件。

  3. 將此物件指派給 DataCacheFactoryConfiguration.SerializationProperties 屬性,並使用 該 DataCacheFactoryConfiguration 物件來設定新的 DataCacheFactory

下列範例示範如何使用程式碼指定名稱為 MyNamespace.MySerializer 的自訂序列化程式。

DataCacheFactoryConfiguration configuration = new DataCacheFactoryConfiguration();

configuration.SerializationProperties = 
   new DataCacheSerializationProperties(DataCacheObjectSerializerType.CustomSerializer, 
   new MyNamespace.MySerializer());

// Assign other DataCacheFactoryConfiguration properties...

// Then create a DataCacheFactory with this configuration
DataCacheFactory factory = new DataCacheFactory(configuration);

建議

如果將自訂序列化程式用於快取,則該快取的所有用戶端在存取該快取內的共用物件時,都必須使用相同版本的自訂序列化程式。