Caducidad de datos en JCache
Esta página explica cómo puede utilizar las políticas de caducidad de JCache con NCache. La página detalla los requisitos previos necesarios para utilizar JCache con NCache, junto con fragmentos de código que demuestran las diferentes políticas de vencimiento que ofrece JCache.
Requisitos previos para la caducidad de datos en JCache
- Para usar JCache con NCache Professional, Reemplace la
ncache-client
ncache-professional-client
en su pom.xml.
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
Importe los siguientes paquetes en su aplicación:
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
Asegúrese de que los datos estén serializados o registrados con NCache formato de serialización.
- Asegúrese de que el caché esté inicializado y ejecutándose.
Agregar elementos con vencimiento de acceso
Note
JCache Caducidad accedida se comporta similar al NCache, Caducidad móvil. Sin embargo, Caducidad accedida No incluye actualizaciones de caché.
El tiempo de vencimiento de un elemento de caché en el AccessedExpiryPolicy
se basa en su última hora de acceso. El siguiente ejemplo crea una instancia del proveedor de almacenamiento en caché de JCache para obtener la instancia de JCacheManager a través de NCache, luego crea un archivo de configuración que especifica el tiempo de vencimiento de un elemento de caché.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
//We are creating a config for object accessed expiration.
//It defines the expiry Duration of a Cache Entry based on the last time it was accessed.
//Accessed does not include a cache update.
MutableConfiguration<String, Product> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new AccessedExpiryPolicy(Duration.FIVE_MINUTES)));
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.createCache("demoCache", config);
Product product = new Product();
product.setProductID("Product:1001");
product.setProductName("Coffee");
product.setPrice(100);
jCache.put("Product:1001", product);
Agregar artículos con vencimiento creado
Note
JCache Caducidad creada se comporta similar al NCache, Caducidad absoluta.
El tiempo de vencimiento de un elemento de caché en el CreatedExpiryPolicy
se basa en su tiempo de creación. Por lo tanto, cualquier actualización del elemento de caché no restablece el tiempo de caducidad. El siguiente ejemplo agrega un elemento de caché con el CreatedExpiryPolicy
.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
//We are creating a config for object creation expiration.
//It defines the expiry Duration of a Cache Entry based on when it was created.
//An update does not reset the expiry time.
MutableConfiguration<String, Product> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new CreatedExpiryPolicy(Duration.FIVE_MINUTES)));
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.createCache("demoCache", config);
Product product = new Product();
product.setProductID("Product:1001");
product.setProductName("Coffee");
product.setPrice(100);
jCache.put("Product:1001", product);
Agregar artículos con vencimiento modificado
Note
JCache Vencimiento modificado se comporta similar al NCache Caducidad móvil. Sin embargo, la caducidad modificada incluye actualizar, modificar y crear una entrada.
La ModifiedExpiryPolicy
define el tiempo de vencimiento de la entrada de caché en función de su última actualización. La actualización puede ser cualquier cambio en la entrada. El siguiente ejemplo agrega un elemento con ModifiedExpiryPolicy
en el caché.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
//We are creating a config for object modified expiration.
//It defines the expiry Duration of a Cache Entry based on the last time it was updated.
//Updating includes created and changing (updating) an entry.
MutableConfiguration<String, Product> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new ModifiedExpiryPolicy(Duration.FIVE_MINUTES)));
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.createCache("demoCache", config);
Product product = new Product();
product.setProductID("Product:1001");
product.setProductName("Coffee");
product.setPrice(100);
jCache.put("Product:1001", product);
Agregar artículos con caducidad eterna
Note
JCache Expiración eterna es similar a cuando no hay una política de vencimiento en NCache.
Un elemento agregado con EternalExpiryPolicy
No caduca. Se desaloja en función de la prioridad de desalojo que se le asigne. El siguiente ejemplo demuestra cómo agregar un elemento en caché con el EternalExpiryPolicy
.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
//We are creating a config for object modified expiration.
//It specifies that Cache Entries won't expire.
//This however doesn't mean they won't be evicted if an underlying implementation needs to free-up resources where by it may choose to evict entries that are not due to expire.
MutableConfiguration<String, Product> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new EternalExpiryPolicy()));
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.createCache("demoCache", config);
Product product = new Product();
product.setProductID("Product:1001");
product.setProductName("Coffee");
product.setPrice(100);
jCache.put("Product:1001", product);
Agregar artículos con vencimiento tocado
Note
JCache Vencimiento tocado se comporta similar al NCache Caducidad móvil. Sin embargo, Toque Caducidad incluye actualizar, modificar y crear una entrada.
La TouchedExpiryPolicy
define la caducidad de un elemento en función del último toque, es decir, la hora en la que se creó, actualizó o se accedió al elemento por última vez. El siguiente ejemplo agrega un elemento en el caché con TouchedExpiryPolicy
.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
//We are creating a configuration for Touched Expiration.
//It defines the expiry Duration of a Cache Entry based on when it was last touched.
//A touch includes creation, update or access.
MutableConfiguration<String, Product> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(new TouchedExpiryPolicy(Duration.FIVE_MINUTES)));
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.createCache("demoCache", config);
Product product = new Product();
product.setProductID("Product:1001");
product.setProductName("Coffee");
product.setPrice(100);
jCache.put("Product:1001", product);
Vea también
Almacenamiento en caché de hibernación
Notificaciones de eventos en caché
NCache Módulo de sesión de Java