Hoy en día, muchas aplicaciones de servidor necesitan coordinar el trabajo con otras aplicaciones y compartir mensajes y datos de forma asincrónica. Y, a menudo, esto se hace en un entorno de alta transacción. Para entornos de alta transacción, NCache es un candidato ideal para estos Comunicaciones asincrónicas basadas en eventos..
NCache proporciona un amplio conjunto de funciones de mensajería y transmisiones para satisfacer las necesidades de estas aplicaciones, incluidas Mensajería de publicación/suscripción, Consultas continuas, Eventos de nivel de artículoy Eventos de nivel de caché. Cada uno se describe a continuación.
NCache proporciona un poderoso Mensajería de publicación/suscripción Plataforma para aplicaciones donde las aplicaciones del Editor pueden enviar mensajes sin saber quiénes son los Suscriptores. Los mensajes se pueden clasificar en Temas y luego los suscriptores pueden suscribirse a temas específicos y recibir estos mensajes de forma asincrónica.
Usted puede fácilmente utilizan el NCache Mensajería Pub/Sub para aplicaciones distribuidas una vez que comprenda los componentes de la mensajería Pub/Sub y su funcionamiento.
A continuación se muestra un ejemplo de código fuente en cómo un editor publica un mensaje a un tema y luego a suscriptor se suscribe al tema.
ITopic topic = _cache.MessagingService.CreateTopic(topicName)
// Creating new message containing a “payload”
var message = new Message(payload);
// Set the expiration TimeSpan of the message
message.ExpirationTime = TimeSpan.FromSeconds(5000);
// Publishing the above created message.
topic.Publish(message, DeliveryOption.All, true);
// Get the already created topic to subscribe to it
ITopic orderTopic = cache.MessagingService.GetTopic(topic);
// Create and register subscribers for the topic created
// MessageRecieved callback is registered
orderTopic.CreateSubscription(MessageReceived);
String topicName = "orderUpdates";
Topic topic = cache.getMessagingService().createTopic(topicName);
// Creating new message containing a “payload”
Customer payload = new Customer("David Jones", "XYZCompany");
var message = new Message(payload);
// Set the expiration TimeSpan of the message
message.setExpirationTime(TimeSpan.FromSeconds(5000));
// Publishing the above created message.
topic.publish(message, DeliveryOption.All, true);
// Get the already created topic to subscribe to it
Topic orderTopic = cache.getMessagingService().getTopic(topicName);
// Create and register subscribers for the topic created
orderTopic.createSubscription(new MessageReceivedListener() {
@Override
public void onMessageReceived(Object sender, MessageEventArgs args) {
// message received
}
});
Consulta continua es una característica poderosa de NCache que le permite monitorear los cambios en un "conjunto de datos" en el caché distribuido basado en una consulta similar a SQL. Usted crea una consulta continua (CQ) con criterios similares a SQL en el caché y la registra con NCache. NCache luego comienza a monitorear cualquier cambio en este “conjunto de datos” en el caché incluyendo:
Así es como puede crear una consulta continua con criterios específicos y registrarse en el servidor.
// Query for required operation
string query = "SELECT $VALUE$ FROM FQN.Customer WHERE Country = ?";
var queryCommand = new QueryCommand(query);
queryCommand.Parameters.Add("Country", "USA");
// Create Continuous Query
var cQuery = new ContinuousQuery(queryCommand);
// Register to be notified when a qualified item is added to the cache
cQuery.RegisterNotification(new QueryDataNotificationCallback(QueryItemCallBack), EventType.ItemAdded, EventDataFilter.None);
// Register continuousQuery on server
cache.MessagingService.RegisterCQ(cQuery);
String cacheName = "demoCache";
// Initialize an instance of the cache to begin performing operations:
Cache cache = CacheManager.getCache(cacheName);
// Query for required operation
String query = "SELECT $VALUE$ FROM com.alachisoft.ncache.sample.Customer WHERE country = ?";
var queryCommand = new QueryCommand(query);
queryCommand.getParameters().put("Country", "USA");
// Create Continuous Query
var cQuery = new ContinuousQuery(queryCommand);
// Register to be notified when a qualified item is added to the cache
cQuery.addDataModificationListener(new QueryDataModificationListener() {
@Override
public void onQueryDataModified(String key, CQEventArg args) {
switch (args.getEventType())
{
case ItemAdded:
// 'key' has been added to the cache
break;
}
}
}, EnumSet.allOf(EventType.class), EventDataFilter.None);
// Register continuousQuery on server
cache.getMessagingService().registerCQ(cQuery);
Para más detalles, puede ver cómo usar consultas continuas en documentos de caché.
Los clientes se registran con NCache para recibir notificaciones de eventos les interesa al proporcionar una función de devolución de llamada. NCache proporciona filtros con eventos que se utilizan para especificar la cantidad de información devuelta con el evento. Estos filtros son Ninguno (predeterminado), metadatos y DatosConMetadatos. Se admiten los siguientes tipos de eventos:
El código que se proporciona a continuación muestra el registro de eventos a nivel de elemento.
public static void RegisterItemLevelEvents()
{
// Get cache
string cacheName = "demoCache";
var cache = CacheManager.GetCache(cacheName);
// Register Item level events
string key = "Product:1001";
cache.MessagingService.RegisterCacheNotification(key, CacheDataNotificationCallbackImpl, EventType.ItemUpdated | EventType.ItemUpdated | EventType.ItemRemoved, EventDataFilter.DataWithMetadata);
}
public static void CacheDataNotificationCallbackImpl(string key, CacheEventArg cacheEventArgs)
{
switch (cacheEventArgs.EventType)
{
case EventType.ItemAdded:
// 'key' has been added to the cache
break;
case EventType.ItemUpdated:
// 'key' has been updated in the cache
break;
case EventType.ItemRemoved:
// 'key' has been removed from the cache
break;
}
}
private static void RegisterItemLevelEvents() throws Exception {
String cacheName = "demoCache";
// Initialize an instance of the cache to begin performing operations:
Cache cache = CacheManager.getCache(cacheName);
String key = "Product:1001";
cache.getMessagingService().addCacheNotificationListener(key, new CacheDataModificationListenerImpl(), EnumSet.allOf(EventType.class), EventDataFilter.DataWithMetadata);
}
private static class CacheDataModificationListenerImpl implements CacheDataModificationListener {
@Override
public void onCacheDataModified(String key, CacheEventArg eventArgs) {
switch (eventArgs.getEventType())
{
case ItemAdded:
// 'key' has been added to the cache
break;
case ItemUpdated:
// 'key' has been updated in the cache
break;
case ItemRemoved:
// 'key' has been removed from the cache
break;
}
}
@Override
public void onCacheCleared(String cacheName) {
//cacheName cleared
}
}
Para eventos a nivel de caché, puede usar la misma devolución de llamada que se usa en los eventos a nivel de elemento.
public static void RegisterCacheLevelEvents()
{
// Get cache
string cacheName = "demoCache";
var cache = CacheManager.GetCache(cacheName);
// Register cache level events
cache.MessagingService.RegisterCacheNotification(EventsSample.CacheDataNotificationCallbackImpl, EventType.ItemUpdated | EventType.ItemUpdated | EventType.ItemRemoved, EventDataFilter.DataWithMetadata);
}
private static void RegisterCacheLevelEvents() throws Exception {
String cacheName = "demoCache";
// Initialize an instance of the cache to begin performing operations:
Cache cache = CacheManager.getCache(cacheName);
CacheEventDescriptor eventDescriptor = cache.getMessagingService().addCacheNotificationListener(new CacheDataModificationListenerImpl(), EnumSet.allOf(EventType.class), EventDataFilter.DataWithMetadata);
}
.NET y Java aplicaciones, NCache es la opción ideal para enviar mensajes Pub/Sub de transacciones altas, consultas continuas y eventos. Aquí está el por qué.
Con esto, puedes usar NCache como una plataforma de mensajería poderosa pero simple. Leer más sobre NCache desde los enlaces a continuación y descargue una versión de prueba de 30 días completamente funcional.