JCache: inizializza la cache
Dopo aver collegato con successo NCache nell'applicazione JCache, è necessaria un'istanza di cache per eseguire operazioni di cache. Le applicazioni Java possono anche interagire con NCache utilizzando il provider API JCache incluso nel pacchetto NCache. Il provider dell'API JCache fornisce un metodo conveniente per inizializzare l'istanza della cache.
Prerequisiti per le operazioni CRUD di JCache
- Per utilizzare JCache con NCache Professional, sostituisci il
ncache-client
conncache-professional-client
nel tuo pom.xml.
<dependency>
<groupId>com.alachisoft.ncache</groupId>
<artifactId>ncache-client</artifactId>
<version>x.x.x</version>
</dependency>
- Includi i seguenti pacchetti e le relative librerie nella tua applicazione da NCache directory di installazione.
import javax.cache.CacheManager
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
Assicurati che i dati siano serializzati o registrati con il file NCache Formato di serializzazione.
Assicurati che la cache sia in esecuzione.
Inizializza cache
Il metodo seguente per ottenere un'istanza di cache in Java consiste nell'utilizzare il file getCache
metodo del JCache CacheManager fornito da NCache. È possibile ottenere un'istanza di una cache precedentemente configurata utilizzando il suo nome (identificatore univoco) come argomento del file getCache
metodo.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache.
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
Ottenere NCache Istanza cache dell'API
NCacheL'API di fornisce funzionalità di memorizzazione nella cache relativamente avanzate, tra cui Blocco, ATTIVITA' E GRUPPI, Messaggistica Pub/Sub, tage simile a SQL funzionalità di query, che possono essere cruciali per scenari complessi, distribuiti e con carico elevato. Per accedere a tutti NCachetramite JCache, puoi utilizzare il file unwrap
metodo fornito da NCache. Questo metodo consente di ottenere un'istanza effettiva di NCache, che può quindi essere utilizzato per accedere e utilizzare tutti i file NCachele capacità di.
Questo esempio crea un'istanza del provider di memorizzazione nella cache JCache che ottiene un'istanza di JCache Manager e quindi esegue il wrapper NCache istanza da esso e ottiene una cache dal gestore tramite il suo nome.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache.
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Unwrapping NCache's cache instance from JCache's cache instance.
com.alachisoft.ncache.client.Cache cache = (com.alachisoft.ncache.client.Cache) jCache.unwrap(com.alachisoft.ncache.client.Cache.class);
Inizializza più cache in una singola applicazione
Per inizializzare più cache in una singola applicazione, è necessario che le cache siano precedentemente configurate e in esecuzione.
//Create an instance of JCache's caching provider to get JCacheManager's instance by NCache.
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
//Get a cache from manager via its string name.
javax.cache.Cache demoCache = manager.getCache("demoCache");
javax.cache.Cache productCache = manager.getCache("productCache");
Aggiungi/aggiorna dati nella cache
Dopo aver eseguito correttamente l'inizializzazione e aver ottenuto un handle di cache, è possibile eseguire a put
operazione. È un'operazione di base fornita da JCache e può essere utilizzata per aggiungere/aggiornare dati alla cache utilizzando più chiamate API.
Aggiunta di oggetti alla cache
Nell'esempio seguente viene creato e aggiunto alla cache un oggetto di una classe personalizzata. Questo elemento ha tutte le proprietà fornite nel codice seguente e viene aggiunto alla cache utilizzando il file put
metodo.
// Ensure that Cache is already initialized and the item exists.
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
String key = "Product:" + product.getProductID();
// Add data in cache with the values
jCache.put(key, product);
Aggiorna i dati nella cache
Nell'esempio seguente, un oggetto di una classe personalizzata viene aggiornato nella cache. IL replace
il metodo sovrascrive il valore già esistente dell'oggetto.
Product product = new Product();
product.setProductID(1001);
product.setProductName("Chai");
product.setUnitsInStock(5); // updated units.
String key = "Product:" + product.getProductID();
// Replace the item in the cache with updated item.
jCache.replace(key, product);
Aggiungi e aggiorna elementi in blocco nella cache
Puoi aggiungere e aggiornare un'intera raccolta di elementi nella cache utilizzando il file putAll
metodo. Questo metodo restituisce una HashMap di tutte le chiavi che non sono state aggiunte insieme all'eccezione.
Product product1 = new Product("1001", "Chai");
String key1 = "Product:" + product1.getProductID();
Product product2 = new Product("1002", "Coffee");
String key2 = "Product:" + product2.getProductID();
// Data to add in cache
HashMap dataMap = new HashMap();
dataMap.put(key1, product1);
dataMap.put(key2, product2);
// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Add/Update all keys in the cache
jCache.putAll(dataMap);
Recupera dalla cache
JCache utilizza get
metodo per recuperare una voce specifica dalla cache tramite chiave.
Recupera un singolo oggetto dalla cache
Nell'esempio seguente utilizziamo il valore predefinito get
metodo per recuperare un oggetto preesistente, "Prodotto: 1001". Questo elemento esiste già nella cache. IL get
Il metodo restituisce un oggetto che deve essere lanciato di conseguenza. Se una chiave corrispondente non esiste nella cache, a null
viene restituito il valore.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Key to get
String key = "Product:1001";
//Get specified item
Product product = (Product) jCache.get(key);
if (product != null) {
// business logic
}
Recupera i dati in blocco dalla cache
Per recuperare una raccolta dalla cache, utilizzare il file getAll
metodo. Questo metodo restituisce una raccolta di elementi come HashMap.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
HashSet keysToGet = new HashSet();
keysToGet.add("Product:1001");
keysToGet.add("Product:1002");
Map productsMap = jCache.getAll(keysToGet);
if (!productsMap.isEmpty())
{
for (Iterator iter = productsMap.values().iterator(); iter.hasNext();)
{
Product product = (Product) iter.next();
//utilize product object accordingly.
}
}
Rimuovere i dati dalla cache
JCache fornisce remove
metodo per rimuovere la mappatura per una chiave esistente dalla cache.
Usando il metodo Rimuovi
Il metodo di rimozione nell'API JCache rimuove la mappatura associata a una chiave specificata dalla cache, se esistente. Il metodo restituisce true (se la cache contiene la chiave e la rimozione ha avuto successo) o false (se non esiste alcuna mappatura per la chiave). L'esempio seguente rimuove le mappature dei tasti per Prodotto classe.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Key to remove.
String key = "Product:1001";
// False is returned if key does not exist in cache.
boolean result = jCache.remove(key);
if (result != true) {
//Deleted.
}
else {
//Failed.
}
Rimuovi i dati in blocco
Il seguente frammento di codice rimuove gli elementi in blocco dalla cache tramite il file removeAll
metodo. Il codice ottiene un'istanza del gestore JCache, ottiene la cache richiesta dal gestore e definisce le chiavi rispetto alle quali devono essere rimossi i dati.
// Get instance of JCacheManager
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Keys to remove
HashSet set = new HashSet();
set.add("Product:1001");
set.add("Product:1002");
// Removing all keys
jCache.removeAll(set);
Cancella cache
Per svuotare completamente la cache (in background), è necessario chiamare il file clear
metodo.
// Get instance of JCacheManager.
CacheManager manager = Caching.getCachingProvider().getCacheManager();
// Get a cache from manager via its string name.
javax.cache.Cache jCache = manager.getCache("demoCache");
// Clear the Cache.
jCache.clear();
Vedere anche
Notifiche di eventi nella cache
Ibernazione della cache
NCache Modulo di sessione Java