Cómo: Recibir notificaciones de una caché de Azure In-Role

Importante

Microsoft recomienda todos los nuevos desarrollos que usen Azure Redis Cache. Para obtener documentación actual e instrucciones sobre cómo elegir una oferta de Azure Cache, consulte ¿Qué oferta de Azure Cache es adecuada para mí?

En este tema se describe cómo agregar una devolución de llamada de notificación de caché que permitirá a la aplicación recibir notificaciones de caché.

Para agregar una devolución de llamada de notificación de caché se requieren dos pasos. En primer lugar, cree un método que deba invocarse cuando una o varias operaciones de caché desencadenen una notificación de caché. El método que invoque con las notificaciones de caché debe aceptar los mismos parámetros que el delegado DataCacheNotificationCallback . En segundo lugar, agregue una devolución de llamada mediante uno de los tres métodos disponibles del objeto DataCache :

Use el parámetro filter para definir los tipos de operaciones de caché que desea que activen notificaciones de caché. Use el nombre del método que creó en el primer paso para el parámetro clientDelegate.

Para agregar una devolución de llamada para una o varias operaciones de caché

  1. Cree el método que desea que active la notificación de caché. Asegúrese de que el método acepte los mismos parámetros que el delegado de DataCacheNotificationCallback.

  2. Agregue una devolución de llamada. Use uno de los tres métodos disponibles del objeto DataCache para definir el ámbito de notificación: AddCacheLevelCallback, AddRegionLevelCallback o AddItemLevelCallback.

    1. Use la enumeración DataCacheOperations en el filter parámetro para especificar qué tipo de operaciones de caché desea desencadenar notificaciones. Para seleccionar más de una enumeración, sepárelas mediante el operador binario OR para realizar una operación OR de bit a bit. Para ello, use el carácter | en C# y el operador Or en Visual Basic.

    2. Use el nombre del método que desea invocar cuando se produzcan estas notificaciones en el parámetro clientDelegate.

    3. Establezca el método de devolución de llamada add igual a un objeto DataCacheNotificationDescriptor que puede usar en otro lugar del programa para quitar la devolución de llamada de notificación de caché.

Ejemplo

El primer paso al registrarse para notificaciones de caché es crear el método que la notificación debe invocar. El método al que llama la notificación debe aceptar los mismos parámetros que el delegado de DataCacheNotificationCallback. En este ejemplo se muestra un método que puede invocar una notificación de caché.

'method invoked by notification "ndCacheLvlAllOps" 
Public Sub myCacheLvlDelegate(ByVal myCacheName As String, _
    ByVal myRegion As String, _
    ByVal myKey As String, _
    ByVal itemVersion As DataCacheItemVersion, _
    ByVal OperationId As DataCacheOperations, _
    ByVal nd As DataCacheNotificationDescriptor)

    'display some of the delegate parameters
    Console.WriteLine("A cache-level notification was triggered!")
    Console.WriteLine("    Cache: " + myCacheName)
    Console.WriteLine("    Region: " + myRegion)
    Console.WriteLine("    Key: " + myKey)
    Console.WriteLine("    Operation: " + OperationId.ToString())
    Console.WriteLine()
End Sub
//method invoked by notification "ndCacheLvlAllOps" 
public void myCacheLvlDelegate(string myCacheName,
    string myRegion, 
    string myKey, 
    DataCacheItemVersion itemVersion,
    DataCacheOperations OperationId, 
    DataCacheNotificationDescriptor nd)
{
    //display some of the delegate parameters
    Console.WriteLine("A cache-level notification was triggered!");
    Console.WriteLine("    Cache: " + myCacheName);
    Console.WriteLine("    Region: " + myRegion);
    Console.WriteLine("    Key: " + myKey);
    Console.WriteLine("    Operation: " + OperationId.ToString());
    Console.WriteLine();
}

El segundo paso es agregar una devolución de llamada para una o varias operaciones de caché. En este ejemplo, se crea una notificación para invocar al método del ejemplo anterior. Exclusivamente para la demostración, esta notificación se configuró para todas las posibles operaciones de caché con un ámbito de notificación en el nivel de caché.

Para definir más de una operación de caché, puede usar el operador binario OR con el fin de asignar más de una enumeración DataCacheOperations a una variable DataCacheOperations que puede usarse para el parámetro de filtro. Para agregar una devolución de llamada para operaciones de caché con un ámbito de notificación en el nivel de caché, use el método AddCacheLevelCallback.

Nota

No se recomienda hacer esta operación en una aplicación de producción. Este ejemplo sirve únicamente como demostración.

'specify all possible item and region operations
Dim allCacheOperations As DataCacheOperations
allCacheOperations = DataCacheOperations.AddItem Or _
    DataCacheOperations.ReplaceItem Or _
    DataCacheOperations.RemoveItem Or _
    DataCacheOperations.CreateRegion Or _
    DataCacheOperations.ClearRegion Or _
    DataCacheOperations.RemoveRegion

'add cache-level notification callback 
'all cache operations from a notifications-enabled cache
Dim ndCacheLvlAllOps as DataCacheNotificationDescriptor = _
    myTestCache.AddCacheLevelCallback(allCacheOperations, AddressOf myCacheLvlDelegate)
//specify all possible item and region operations
DataCacheOperations allCacheOperations = DataCacheOperations.AddItem |
    DataCacheOperations.ReplaceItem |
    DataCacheOperations.RemoveItem |
    DataCacheOperations.CreateRegion |
    DataCacheOperations.ClearRegion |
    DataCacheOperations.RemoveRegion;

//add cache-level notification callback 
//all cache operations from a notifications-enabled cache
DataCacheNotificationDescriptor ndCacheLvlAllOps
    = myTestCache.AddCacheLevelCallback(allCacheOperations, myCacheLvlDelegate);

En el siguiente ejemplo se muestra el resultado de agregar una devolución de llamada para una operación de caché con un ámbito de notificación en el nivel de región, que solamente se activa cuando se agrega a la memoria caché una región denominada TestRegion.

'add region-level notification callback for region "TestRegion"
'trigger notification with CreateRegion operation
Dim ndRegionCreateRegOp As DataCacheNotificationDescriptor
ndRegionCreateRegOp = _
    myTestCache.AddRegionLevelCallback("TestRegion", _
    DataCacheOperations.CreateRegion, AddressOf myRegionLvlAddDelegate)
//add region-level notification callback for region "TestRegion"
//trigger notification with CreateRegion operation
DataCacheNotificationDescriptor ndRegionCreateRegOp
    = myTestCache.AddRegionLevelCallback("TestRegion",
    DataCacheOperations.CreateRegion, myRegionLvlAddDelegate);

En el siguiente ejemplo se muestra el resultado de agregar una devolución de llamada para operaciones de caché con un ámbito de notificación en el nivel de elemento, que solamente se activa cuando se agrega o se reemplaza un objeto en la memoria caché mediante la clave TestKey.

Nota

Solo las operaciones de elemento AddItem, ReplaceItem y RemoveItem pueden desencadenar las notificaciones de caché con devoluciones de llamada de nivel de elemento. Al agregar una devolución de llamada en el nivel de elemento, especificar operaciones de región en el parámetro de filtro provocará una excepción.

'add item-level notification callback for item "TestKey"
'trigger notification with AddItem and ReplaceItem operations
Dim ndItemUpdateOps As DataCacheNotificationDescriptor
ndItemUpdateOps = _
    myTestCache.AddItemLevelCallback("TestKey", _
    (DataCacheOperations.AddItem Or DataCacheOperations.ReplaceItem), _
    AddressOf myItemLvlUpdateDelegate)
//add item-level notification callback for item "TestKey"
//trigger notification with AddItem and ReplaceItem operations
DataCacheNotificationDescriptor ndItemUpdateOps
    = myTestCache.AddItemLevelCallback("TestKey",
        (DataCacheOperations.AddItem | DataCacheOperations.ReplaceItem),
        myItemLvlUpdateDelegate);

Para quitar una devolución de llamada de notificación de caché

  1. Use el método RemoveCallback para quitar la devolución de llamada de notificación de caché. Use el objeto DataCacheNotificationDescriptor adecuado para el parámetro nd. Use el NotificationDescriptor que recibió al registrarse para notificar que desea dejar de recibir notificaciones.

Ejemplo

En este ejemplo, el cliente de caché y tres objetos DataCacheNotificationDescriptor se declaran en el nivel de clase para que puedan acceder a ellos mediante métodos que agregan y quitan devoluciones de llamada.

'define variables for class
Dim myTestCache As DataCache
Dim ndCacheLvlAllOps As DataCacheNotificationDescriptor
Dim ndRegionLvlAllOps As DataCacheNotificationDescriptor
Dim ndItemLvlAllOps As DataCacheNotificationDescriptor
//define variables for class
DataCache myTestCache;
DataCacheNotificationDescriptor ndCacheLvlAllOps;
DataCacheNotificationDescriptor ndRegionLvlAllOps;
DataCacheNotificationDescriptor ndItemLvlAllOps;

En este ejemplo se muestra un método que usa el método RemoveCallback para quitar las devoluciones de llamada correspondientes a los tres objetos DataCacheNotificationDescriptor del ejemplo anterior.

'remove cache notification callbacks
Public Sub RemoveNotificationCallbacks()
    myTestCache.RemoveCallback(ndCacheLvlAllOps)
    myTestCache.RemoveCallback(ndRegionLvlAllOps)
    myTestCache.RemoveCallback(ndItemLvlAllOps)
End Sub
//remove cache notification callbacks
public void RemoveNotificationCallbacks()
{
    myTestCache.RemoveCallback(ndCacheLvlAllOps);
    myTestCache.RemoveCallback(ndRegionLvlAllOps);
    myTestCache.RemoveCallback(ndItemLvlAllOps);
}