Establece comportamiento y uso en caché
Un HashSet es una estructura de datos desordenada que no contiene valores duplicados. Por ejemplo, se puede usar un HashSet para almacenar la ID de usuario de todos los usuarios que inician sesión en un sitio de comercio electrónico en un día determinado. Si el usuario inicia sesión nuevamente, la ID no se almacena ya que no se permiten valores duplicados.
NCache mejora aún más HashSet proporcionando NCache características específicas como Grupos, Etiquetas, Vencimiento, Cerraduras, Dependencias, y más.
Comportamiento
- Un HashSet solo puede ser de tipo primitivo.
- Se nombran los HashSets. Por lo tanto, debe proporcionar una clave de caché única para cada HashSet.
- Nulo no es un tipo de valor admitido.
- No se admiten valores duplicados.
Requisitos previos
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: Dolor, IDistributedHashSetDistributedHashSetIDistributedHashSet, Administrador de tipo de datos IData, CrearHashSet, ObtenerHashSet, TiendaUnion, TiendaIntersección, Diferencia de tienda, Eliminar, RegistroNotificación, Tipo de datosNotificación de datosDevolución de llamada, Tipo de evento, Tipo de datosEventoFiltro de datos, Bloquear, descubrir.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: cache, DistributedHashSetDistributedHashSet, getDataStructuresManager, crearHashSet, obtenerHashSet, tiendaUnion, tiendaIntersección, tiendadiferencia, Tipo de evento, obtener tipo de evento, Estructura de datosDataChangeListener, onDataStructureCambiado, DataStructureEventArgDataStructureEventArg, Tipo de datosEventoFiltro de datos, obtener artículo de colección, bloquear, desbloquear.
- Para obtener información sobre los requisitos previos estándar necesarios para trabajar con todos NCache características del lado del cliente, consulte la página proporcionada en Requisitos previos de la API del lado del cliente.
- Para obtener detalles de la API, consulte: cache, DistributedHashSetDistributedHashSet, Administrador de estructuras de datos, get_data_structures_manager, crear_hashset, get_hashset, unión_tienda, intersección_tienda, tienda_diferencia, obtener_iterador, remove, eliminar_aleatorio, get_event_type, Tipo de datosEventoFiltro de datos, Filtro de datos de evento.
Crear HashSet y agregar datos
Note
Un conjunto no puede contener valores duplicados.
El siguiente ejemplo de código crea dos HashSets de tipo int en el caché usando CreateHashSet
para los usuarios que inician sesión los lunes y martes. Luego agrega datos a estos dos HashSets.
// Precondition: Cache must be connected
// Create unique keys for HashSets
string mondayUsersKey = "MondayUsers";
string tuesdayUsersKey = "TuesdayUsers";
// Create HashSets of int type
IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.CreateHashSet<int>(mondayUsersKey);
// Add user IDs for Monday
userSetMonday.Add(1223);
userSetMonday.Add(34564);
userSetMonday.Add(3564);
IDistributedHashSet<int> userSetTuesday = cache.DataTypeManager.CreateHashSet<int>(tuesdayUsersKey);
// Add userIDs for Tuesday
UserSetTuesday.Add(4545);
UserSetTuesday.Add(34564);
UserSetTuesday.Add(3564);
UserSetTuesday.Add(7879);
// Precondition: Cache must be connected
// Create unique keys for HashSets
String mondayUsersKey = "MondayUsers";
String tuesdayUsersKey = "TuesdayUsers";
// Create HashSets of int type
DistributedHashSet userSetMonday = cache.getDataStructuresManager().createHashSet(mondayUsersKey, Integer.class);
// Add user IDs for Monday
userSetMonday.add(1223);
userSetMonday.add(34564);
userSetMonday.add(3564);
DistributedHashSet userSetTuesday = cache.getDataStructuresManager().createHashSet(tuesdayUsersKey, Integer.class);
// Add userIDs for Tuesday
userSetTuesday.add(4545);
userSetTuesday.add(34564);
userSetTuesday.add(3564);
userSetTuesday.add(7879);
# Precondition: Cache is already connected
# HashSet with this key already exists in cache
monday_user_key = "MondayUsers"
tuesday_user_key = "TuesdayUsers"
# Create HashSets of int type
user_set_monday = cache.get_data_structures_manager.create_hashset(monday_user_key, int)
# Add user IDs for Monday
user_set_monday.add(1223)
user_set_monday.add(34564)
user_set_monday.add(3564)
user_set_tuesday = cache.get_data_structures_manager.create_hashset(tuesday_user_key, int)
# Add user IDs for Tuesday
user_set_monday.add(4545)
user_set_monday.add(34564)
user_set_monday.add(3564)
user_set_monday.add(7879)
Note
Para garantizar que la operación sea a prueba de fallas, se recomienda manejar cualquier posible excepción dentro de su aplicación, como se explica en Manejo de fallas.
NCache también proporciona soporte para operaciones nativas de HashSet como Union
, Intersection
y Difference
. El siguiente ejemplo de código crea tres HashSets del tipo int que almacenan el Union
, Intersection
y Difference
de los dos HashSets usuarioSetMonday y usuarioSetMartes creado en el ejemplo anterior:
// Create unique keys for HashSets
string totalUsersKey = "TotalUsers";
string weeklyUsersKey = "WeeklyUsers";
string differenceKey = "Difference";
// Create HashSets of int type
IDistributedHashSet<int> userSetTotal = cache.DataTypeManager.CreateHashSet<int>(totalUsersKey);
IDistributedHashSet<int> userSetWeekly = cache.DataTypeManager.CreateHashSet<int>(weeklyUsersKey);
IDistributedHashSet<int> userSetDifference = cache.DataTypeManager.CreateHashSet<int>(differenceKey);
// userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
userSetMonday.StoreUnion(totalUsersKey, tuesdayUsersKey);
// userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
userSetMonday.StoreIntersection(weeklyUsersKey, tuesdayUsersKey);
// userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
userSetMonday.StoreDifference(differenceKey, tuesdayUsersKey);
// Precondition: Cache must be connected
// Create unique keys for HashSets
String totalUsersKey = "TotalUsers";
String weeklyUsersKey = "WeeklyUsers";
String differenceKey = "Difference";
// Create HashSets of int type
DistributedHashSet userSetTotal = cache.getDataStructuresManager().createHashSet(totalUsersKey, Integer.class);
DistributedHashSet userSetWeekly = cache.getDataStructuresManager().createHashSet(weeklyUsersKey, Integer.class);
DistributedHashSet userSetDifference = cache.getDataStructuresManager().createHashSet(differenceKey, Integer.class);
// userSetTotal will contain unique values from the HashSets userSetMonday and userSetTuesday after union
userSetMonday.storeUnion(totalUsersKey, tuesdayUsersKey);
// userSetWeekly will contain common values from the HashSets userSetMonday and userSetTuesday after intersection
userSetMonday.storeIntersection(weeklyUsersKey, tuesdayUsersKey);
// userSetDifference will contain the difference between the HashSets userSetMonday and userSetTuesday
userSetMonday.storeDifference(differenceKey, tuesdayUsersKey);
# Precondition: Cache is already connected
# HashSet with this key already exists in cache
total_users_key = "TotalUsers"
weekly_users_key = "WeeklyUsers"
difference_key = "Difference"
# Create HashSets of int type
user_set_total = cache.get_data_structures_manager.create_hashset(total_users_key, int)
user_set_weekly = cache.get_data_structures_manager.create_hashset(weekly_users_key, int)
user_set_difference = cache.get_data_structures_manager.create_hashset(difference_key, int)
# user_set_total will contain unique values from the HashSets total_users_key and tuesday_users_key after union
user_set_total.store_union(total_users_key, tuesday_users_key)
# user_set_weekly will contain common values from the HashSets weekly_users_key and tuesday_users_key after intersection
user_set_weekly.store_intersection(weekly_users_key, tuesday_users_key)
# user_set_difference will contain the difference between the HashSets difference_key and tuesday_users_key
user_set_difference.store_difference(difference_key, tuesday_users_key)
Obtener HashSet de caché
Puede obtener un HashSet del caché usando GetHashSet
que toma una clave de caché como parámetro. Esta clave es el nombre del HashSet, que se especifica durante la creación del HashSet.
advertencia
Si el elemento que se busca no es del tipo HashSet, un Type mismatch
Se lanza una excepción.
// HashSet with this key already exists in cache
string key = "ProductIDSet";
// Get HashSet and show items of HashSet
IDistributedHashSet<int> retrievedHashSet = cache.DataTypeManager.GetHashSet<int>(key);
if (retrievedHashSet != null)
{
foreach (var item in retrievedHashSet)
{
// Perform operations
}
}
else
{
// HashSet does not exist
}
// Precondition: Cache is already connected
// HashSet with this key already exists in cache
String key = "ProductIDSet";
// Get HashSet and show items of HashSet
DistributedHashSet retrievedHashSet = cache.getDataStructuresManager().getHashSet(key, Integer.class);
if (retrievedHashSet != null) {
for (var item : retrievedHashSet) {
// Perform operations
}
} else {
// HashSet does not exist
}
# Precondition: Cache is already connected
# HashSet with this key already exists in cache
key = "ProductIDSet"
# Get hashset and show items of hashset
retrieved_hash_set = cache.get_data_structures_manager().get_hashset(key, int)
if retrieved_hash_set is not None:
for item in retrieved_hash_set.get_iterator():
# Perform operations
print(item)
else:
# HashSet does not exist
print("Set not found")
Eliminar elementos de HashSet
Los elementos se pueden eliminar de un HashSet ya sea especificando el elemento en sí o al azar. El siguiente ejemplo de código elimina los usuarios del lunes del HashSet de usuarios semanales (que ya se han agregado a la memoria caché).
// Get existing HashSets
string userIDMondayKey = "UserIDMonday";
string userIDWeeklyKey = "UserIDWeekly";
IDistributedHashSet<int> userSetMonday = cache.DataTypeManager.GetHashSet<int>(userIDMondayKey);
IDistributedHashSet<int> usersWeekly = cache.DataTypeManager.GetHashSet<int>(userIDWeeklyKey);
// Remove users of Monday from Weekly HashSet
var removedItem = usersWeekly.Remove(userSetMonday);
// Precondition: Cache must be connected
// Get existing HashSets
String userIDMondayKey = "UserIDMonday";
String userIDWeeklyKey = "UserIDWeekly";
DistributedHashSet userSetMonday = cache.getDataStructuresManager().getHashSet(userIDMondayKey, Integer.class);
DistributedHashSet usersWeekly = cache.getDataStructuresManager().getHashSet(userIDWeeklyKey, Integer.class);
// Remove users of Monday from Weekly HashSet
var removedItem = usersWeekly.remove(userSetMonday);
# Precondition: Cache must be connected
# Get existing HashSets
user_id_monday_key = "UserIDMonday"
user_id_weekly_key = "UserIDWeekly"
user_set_monday = cache.get_data_structures_manager().get_hashset(user_id_monday_key, int)
users_weekly = cache.get_data_structures_manager().get_hashset(user_id_weekly_key, int)
# Remove users of Monday from Weekly set
users_weekly.remove(user_set_monday)
# Remove Random users from weekly set
users_weekly.remove_random()
Notificaciones de eventos en HashSet
Puede registrar eventos de caché, eventos basados en claves y eventos de estructura de datos en una estructura de datos como un HashSet. Para el comportamiento, consulte comportamiento inteligente.
El siguiente ejemplo de código registra un evento de caché de ItemAdded
y ItemUpdated
así como registra un evento para ItemAdded
y ItemUpdated
en el caché configurado. Una vez que se crea un HashSet en el caché, un ItemAdded
Se activa el evento a nivel de caché. Sin embargo, una vez que se agrega un elemento al HashSet, un ItemAdded
se activa un evento de estructura de datos y ItemUpdated
se activa el evento de nivel de caché.
Registrar evento en HashSet creado
// Unique cache key for hashset
string key = "UserIDMonday";
// Create hashset
IDistributedHashSet<int> hashset = cache.DataTypeManager.CreateHashSet<int>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on HashSet created
// DataTypeNotificationCallback is callback method specified
hashset.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
DataTypeEventDataFilter.Data);
// Perform operations
// Precondition: Cache is already connected
// Unique cache key for hashset
String key = "UserIDMonday";
// Create HashSet
DistributedHashSet<Integer> hashSet = cache.getDataStructuresManager().createHashSet(key, Integer.class);
// Create EnumSet of event types
EnumSet<EventType> enumSet = EnumSet.of(com.alachisoft.ncache.runtime.events.EventType.ItemAdded,
EventType.ItemUpdated, EventType.ItemRemoved);
// Register ItemAdded, ItemUpdated, ItemRemoved events on HashSet created
// dataChangeListener is the specified callback method
DataStructureDataChangeListener dataChangeListener = dataStructureListener.onDataStructureChanged(collectionName, args);
hashSet.addChangeListener(dataChangeListener, enumSet, DataTypeEventDataFilter.Data);
// Perform operations
def datastructure_callback_function(collection_name, collection_event_args):
# Perform Operations
print("Event Fired for " + str(collection_name))
# Precondition: Cache is already connected
# Unique cache key for hashset
key = "UserIDMonday"
# Create hashset
monday_user_set = cache.get_data_structures_manager().create_hashset(key, int)
# Register ItemAdded, ItemUpdated, ItemRemoved events on hashset created
events_list = [ncache.EventType.ITEM_ADDED, ncache.EventType.ITEM_UPDATED, ncache.EventType.ITEM_REMOVED]
monday_user_set.add_change_listener(datastructure_callback_function, events_list, ncache.DataTypeEventDataFilter.DATA)
# Perform operations
Especificar devolución de llamada para notificación de eventos
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
switch (collectionEventArgs.EventType)
{
case EventType.ItemAdded:
// Item has been added to the collection
break;
case EventType.ItemUpdated:
if (collectionEventArgs.CollectionItem != null)
{
// Item has been updated in the collection
// Perform operations
}
break;
case EventType.ItemRemoved:
// Item has been removed from the collection
break;
}
}
DataStructureDataChangeListener dataStructureListener = new DataStructureDataChangeListener() {
@Override
public void onDataStructureChanged(String collection, DataStructureEventArg dataStructureEventArg) {
switch (dataStructureEventArg.getEventType()) {
case ItemAdded:
// Item has been added to the collection
break;
case ItemUpdated:
if (dataStructureEventArg.getCollectionItem() != null) {
//Item has been updated in the collection
// perform operations
}
break;
case ItemRemoved:
//Item has been removed from the collection
break;
}
}
};
def datastructure_callback_function(collection_name: str, collection_event_args: DataStructureEventArg):
if collection_event_args.get_event_type() is ncache.EventType.ITEM_ADDED:
# Item has been added to the collection
print("Item added in " + collection_name)
elif collection_event_args.get_event_type() is ncache.EventType.ITEM_UPDATED:
# Item has been updated in the collection
print("Item updated in " + collection_name)
elif collection_event_args.get_event_type() is ncache.EventType.ITEM_REMOVED:
# Item has been removed from the collection
print("Item removed from " + collection_name)
HashSet de bloqueo
Un HashSet se puede bloquear y desbloquear explícitamente para garantizar la coherencia de los datos. El siguiente ejemplo de código crea un HashSet y lo bloquea durante un período de 10 segundos usando Bloquear y luego lo desbloquea usando descubrir.
// HashSet exists with key "UserIDMonday" Cache Key
string key = "UserIDMonday";
// Get HashSet
IDistributedHashSet<int> hashset = cache.DataTypeManager.GetHashSet<int>(key);
// Lock HashSet for 10 seconds
bool isLocked = hashset.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// HashSet is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// HashSet is not locked because either:
// HashSet is not present in the cache
// HashSet is already locked
}
hashset.Unlock();
// Precondition: Cache is already connected
// HashSet exists with key "UserIDMonday" Cache Key
String key = "UserIDMonday";
// Get HashSet
DistributedHashSet hashset = cache.getDataStructuresManager().getHashSet(key, Integer.class);
// Lock HashSet for 10 seconds
boolean isLocked = hashset.lock(TimeSpan.FromSeconds(10));
if (isLocked) {
// HashSet is successfully locked for 10 seconds
// Unless explicitly unlocked
} else {
// HashSet is not locked because either:
// HashSet is not present in the cache
// HashSet is already locked
}
hashset.unlock();
Recursos adicionales
NCache proporciona una aplicación de muestra para la estructura de datos HashSet en GitHub.
Vea también
.NETO: Alachisoft.NCache.Client.Tipos de datos espacio de nombres
Java: com.alachisoft.ncache.cliente.estructuras de datos espacio de nombres
Pitón: ncache.cliente.estructuras de datos clase.