• Facebook
  • Twitter
  • Youtube
  • Allineato
  • RSS
  • Docs
  • Confronti
  • Blog
  • Scaricare
  • Contattaci
Scaricare
Mostra/Nascondi sommario

Scadenza assoluta dei dati nella cache

Scadenza assoluta in NCache Garantisce la coerenza dei dati invalidando gli elementi della cache a una data e ora precise, definite dal cliente. È possibile specificare una scadenza assoluta per gli elementi che devono rimanere nella cache per un periodo di tempo limitato. Ad esempio, un'azienda annuncia una vendita lampo di 24 ore su determinati prodotti. Questi elementi possono quindi essere memorizzati nella cache con una scadenza assoluta di 24 ore, in modo da essere rimossi dalla cache non appena la vendita termina.

Inoltre, questo DateTime il valore viene convertito in Ora UTC per gestire scenari in cui il server di cache e il client si trovano in fusi orari diversi. Pertanto, gli elementi scadranno esattamente all'ora specificata dall'utente.

Prerequisiti

Prima di usare il NCache Le API lato client devono garantire il rispetto dei seguenti prerequisiti:

  • .NET
  • Java
  • Python
  • Node.js
  • API legacy
  • Installa i seguenti pacchetti NuGet nella tua applicazione client .NET:
    • Enterprise: Alachisoft.NCache.Sdk
    • Open source: Alachisoft.NCache.SDK open source
  • Includere i seguenti spazi dei nomi nell'applicazione:
    • Alachisoft.NCache.Cliente
    • Alachisoft.NCache.Eccezioni.di.runtime
    • Alachisoft.NCache.Memorizzazione.della.cache
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: ICache, CacheItem, CacheItemAttributes, contiene, Contare, Scadenza, inserire, Aggiorna attributi.
  • Aggiungi le seguenti dipendenze Maven per la tua applicazione client Java in pom.xml file:
<dependency>
    <groupId>com.alachisoft.ncache</groupId>
    <!--for NCache Enterprise-->
    <artifactId>ncache-client</artifactId>
    <version>x.x.x</version>
</dependency>
  • Importa i seguenti pacchetti nell'applicazione client Java:
    • importare com.alachisoft.ncache.client.*;
    • importare com.alachisoft.ncache.runtime.eccezione.*;
    • importare com.alachisoft.ncache.runtime.caching.*;
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, CacheItemAttributes, contiene, getCount, Scadenza, insert, updateAttributes.
  • Installa i seguenti pacchetti nella tua applicazione client Python:
    • Enterprise: client ncache
  • Importa i seguenti pacchetti nella tua applicazione:
    • da ncache.client import *
    • da ncache.runtime.caching importazione *
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, CacheItemAttributes, contiene, Scadenza, insert, update_attributes.
  • Installa e includi il seguente modulo nella tua applicazione client Node.js:
    • Enterprise: client ncache
  • Includi la seguente classe nella tua applicazione:
    • Cache
    • Scadenza
  • La cache deve essere in esecuzione.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Per i dettagli dell'API, fare riferimento a: Cache, CacheItem, CacheItemAttributes, contiene, getCount, Scadenza, insert, updateAttributes.
  • Installa uno dei seguenti pacchetti NuGet nella tua applicazione client .NET:
    • Enterprise: Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
  • Crea una nuova applicazione console.
  • Assicurati che i dati aggiunti lo siano serializzabile.
  • Aggiungi NCache Referenze individuando %NCHOME%\NCache\bin\assembly\4.0 e aggiungendo Alachisoft.NCache.Web and Alachisoft.NCache.Runtime come appropriato.
  • Includi il Alachisoft.NCache.Web.Caching spazio dei nomi nell'applicazione.
  • Per saperne di più sul NCache API legacy, scaricala NCache 4.9 documenti disponibili come file .zip file sul Alachisoft Sito web.

Come aggiungere o aggiornare elementi con scadenza assoluta

Insert è lo standard NCache API per sincronizzare lo stato dell'applicazione con la cache. Puoi facilmente aggiungere o aggiornare gli elementi della cache per impostare la scadenza utilizzando l'API inserire metodo. Il CacheItem è una classe personalizzata fornita da NCache che può essere utilizzato per aggiungere dati alla cache e consente anche di impostare metadati aggiuntivi associati all'oggetto. Questi metadati definiscono le proprietà dell'elemento, come la scadenza, le dipendenze e altro ancora.

L'esempio seguente imposta il valore di Expiration proprietà a una scadenza assoluta di 5 minuti per un CacheItem. Aggiunge il CacheItem nella cache se la chiave non esiste e la aggiorna se esiste. Questo CacheItem verrà quindi rimosso dalla cache dopo 5 minuti.

Consiglio

Puoi monitorare/verificare la scadenza tramite:

  • Contatore "Conteggio cache" nel file NCache Monitorare or Contatori PerfMon.
  • utilizzando cache.Contains una volta trascorso l'intervallo di scadenza.
  • utilizzando cache.Count prima e dopo aver specificato la scadenza.
  • .NET
  • Java
  • Python
  • Node.js
  • API legacy
try
{
  // Precondition: Cache is already connected
  // Get product from database against given product ID
  Product product = FetchProductFromDB(1001);

  // Generate a unique cache key for this product
  string key = $"Product:{product.ProductID}";

  // Create a new CacheItem for this product
  var cacheItem = new CacheItem(product);

  // Set Expiration TimeSpan
  var expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(5));

  cacheItem.Expiration = expiration;

  // Add/Update item with expiration
  cache.Insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures 
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
try
{
  // Precondition: Cache is already connected
  // Get product from database against given product ID
  Product product = fetchProductFromDB(1001);

  // Generate a unique cache key for this product
  String key = "Product:" + product.getProductID();

  // Create a new CacheItem for this product
  CacheItem cacheItem = new CacheItem(product);

  // Set Expiration type and TimeSpan
  Expiration expiration = new Expiration(ExpirationType.Absolute, TimeSpan.FromMinutes(5));

  cacheItem.setExpiration(expiration);

  // Add/Update item in cache with expiration
  cache.insert(key, cacheItem);
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like IllegalArgumentException or NullPointerException 
}
try:
    # Precondition: Cache is already connected
    # Get product from database against given product ID
    product = fetch_product_from_db()

    # Generate a unique cache key for this product
    key = "Product:" + product.get_product_id()

    # Create a new CacheItem for this product
    cache_item = ncache.CacheItem(product)

    # Set Expiration type and TimeSpan
    expiration = ncache.Expiration(ncache.ExpirationType.ABSOLUTE, ncache.TimeSpan.from_minutes(5))

    cache_item.set_expiration(expiration)

    # Add/Update item in cache with expiration
    cache.insert(key, cache_item)

except Exception as error:
    # Exception can occur due to:
    # Connection Failures
    # Operation Timeout
    # Operation during state transfer
    print("An error occurred:", str(error))
try
{
  // This is an async method
  // Precondition: Cache is already connected
  // Get product from database against given product ID
  var product = this.fetchProductFromDB(1001);

  // Generate a unique cache key for this product
  var key = "Product:" + product.getProductID();

  // Create a new CacheItem for this product
  // You also need to specify the FQN (Fully Qualified Name) of the class
  var cacheItem = new ncache.CacheItem(product,"FQN.Product");

  // Set Expiration type and TimeSpan
  var expiration = new ncache.Expiration(ncache.ExpirationType.Absolute, ncache.TimeSpan.FromMinutes(5));

  cacheItem.setExpiration(expiration);

  // Add/Update item in cache with expiration
  await this.cache.insert(key, cacheItem);
}
catch (error)
{
    // Handle errors
}
// Using NCache Enterprise 4.9.1

try
{
  // Precondition: Cache is already connected
  // Get product from database against given product ID
  Product product = FetchProductFromDB(1001);

  // Generate a unique cache key for this product
  string key = $"Product:{product.ProductID}";
  CacheItem cacheItem = new CacheItem(product);

  // Updating absolute expiration of 5 min through Add API.
  cache.Insert(key, product, null, System.DateTime.Now.AddMinutes(5), Cache.NoSlidingExpiration, CacheItemPriority.Default);
}
catch (OperationFailedException ex)
{
    // Exception can occur due to:
    // Connection Failures 
    // Operation Timeout
    // Operation performed during state transfer
}
catch (Exception ex)
{
    // Any generic exception like ArgumentNullException or ArgumentException
}
Note:

Per garantire che l'operazione sia a prova di errore, si consiglia di gestire eventuali potenziali eccezioni all'interno dell'applicazione, come spiegato in Gestione dei guasti.

Come aggiungere o aggiornare elementi con scadenze predefinite configurate

utilizzando DefaultAbsolute consente di gestire i dati tramite valori configurati nel NCache Centro Direzionale o config.ncconf senza richiedere ridistribuzioni del codice applicativo. È possibile specificare la scadenza assoluta nell'API utilizzando DefaultAbsolute and DefaultAbsoluteLonger. Ciò offre la flessibilità di modificare il valore esternamente, se necessario, senza modificare il codice.

Il codice seguente associa la Scadenza predefinita configurata (DefaultAbsolute in questo caso) con un elemento e lo aggiunge alla cache se la chiave non esiste, e aggiorna l'elemento con la scadenza se la chiave esiste. Una volta trascorso il tempo configurato, l'elemento scade.

Consigli

Per abilitare la scadenza predefinita, è necessario abilitarla tramite NCache Centro di gestione or config.ncconf.

  • .NET
  • Java
  • Python
  • Node.js
  • API legacy
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);

// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";

// Create a CacheItem instance for the product
var cacheItem = new CacheItem(product);

// Set Expiration type
var expiration = new Expiration(ExpirationType.DefaultAbsolute);

cacheItem.Expiration = expiration;

// Add/Update the item in the cache with default expiration
CacheItemVersion version = cache.Insert(key, cacheItem);
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = fetchProductFromDB(1001);

// Generate a unique cache key for this product
String key = "Product:" + product.getProductID();

// Create a CacheItem instance for the product
CacheItem cacheItem = new CacheItem(product);

// Set Expiration type
Expiration expiration = new Expiration(ExpirationType.DefaultAbsolute);

cacheItem.setExpiration(expiration);

// Add/Update the item in the cache with default expiration
CacheItemVersion version = cache.insert(key, cacheItem);
# Precondition: Cache is already connected
# Get product from database
product = fetch_product_from_db()

# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()

# Create a new CacheItem for this product
cache_item = ncache.CacheItem(product)

# Set Expiration type and TimeSpan
expiration = ncache.Expiration(ncache.ExpirationType.DEFAULT_ABSOLUTE)

cache_item.set_expiration(expiration)

# Add/Update item in cache with expiration
version = cache.insert(key, cache_item)
// Precondition: Cache is already connected
// This is an async method
// Get product from database against given product ID
var product = this.fetchProductFromDB(1001);

// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();

// Create a CacheItem instance for the product
// You also need to specify the FQN(Fully Qualified Name) of the class
var cacheItem = new ncache.CacheItem(product,"FQN.Product");

// Set Expiration TimeSpan
var expiration = new ncache.Expiration(ncache.ExpirationType.DefaultAbsolute);

cacheItem.setExpiration(expiration);

var version = await this.cache.insert(key, cacheItem);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

// Get product from database against given product ID
Product product = FetchProductFromDB("1001");

// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
CacheItem cacheItem = new CacheItem(product);

// Updating absolute expiration of 5 min through Add API.
cache.Insert(key, product, null, Cache.DefaultAbsolute, Cache.NoSlidingExpiration, CacheItemPriority.Default);

Come impostare la scadenza assoluta per gli elementi della cache esistenti

NCache fornisce inoltre la flessibilità di impostare la scadenza assoluta su un elemento della cache esistente senza doverlo reinserire nella cache. Questo viene fatto tramite CacheItemAttributes classe, che ha il AbsoluteExpiration proprietà da impostare sull'elemento della cache. Questo imposta la data e l'ora esatte in cui l'elemento deve essere invalidato nella cache. L'attributo viene quindi applicato alla chiave esistente dell'elemento, utilizzando il UpdateAttributes metodo di ICache.

L'esempio seguente imposta la scadenza assoluta per un elemento già presente nella cache senza una data di scadenza predefinita. Ciò elimina la necessità di aggiungere o reinserire l'elemento nella cache.

  • .NET
  • Java
  • Python
  • Node.js
  • API legacy
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
string key = "Product:1001";

// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
var attr = new CacheItemAttributes();
attr.AbsoluteExpiration = DateTime.Now.AddSeconds(5);

// Set Absolute Expiration of 5 seconds against existing key
cache.UpdateAttributes(key, attr);
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
String key = "Product:1001";

// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 5);

CacheItemAttributes attr = new CacheItemAttributes();

attr.setAbsoluteExpiration(calendar.getTime());

// Set Absolute Expiration of 5 seconds against existing key
cache.updateAttributes(key, attr);
# Precondition: Cache is already connected
# Precondition: Item already exists in cache
key = "Product:1001"

# Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
time = datetime.now() + timedelta(seconds=5)
attr = ncache.CacheItemAttributes()

attr.set_absolute_expiration(time)

# Set Absolute Expiration of 5 seconds against existing key
cache.update_attributes(key, attr)
// This is an async method
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
var key = "Product:1001";

// Create a CacheItemAttribute for absolute expiration and set its value to 5 seconds
var time = new Date().getSeconds()+5;
var attr = new ncache.CacheItemAttributes();

attr.setAbsoluteExpiration(time);

// Set Absolute Expiration of 5 seconds against existing key
await this.cache.updateAttributes(key, attr);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Precondition: Item already exists in cache
string key = "1001";

// Get product from database against given product ID
Product product = FetchProductFromDB(key);

//updating AbsoluteLonger expiration with configured value
cache.Insert(key, product, null, Cache.DefaultAbsoluteLonger, Cache.NoSlidingExpiration, CacheItemPriority.Default);

Risorse addizionali

NCache fornisce un'applicazione di esempio per Absolute Expiration on GitHub.

Vedere anche

.NETTO: Alachisoft.NCache.Memorizzazione.della.cache spazio dei nomi.
Giava: com.alachisoft.ncache.runtime.caching spazio dei nomi.
Pitone: memorizzazione nella cache di ncache.runtime modulo.
Node.js: Scadenza classe.

Contattaci

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
E-MAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Confronto edizione
  • NCache Architettura
  • Parametri di riferimento
Scaricare
Prezzi
Prova Parco giochi

Distribuzioni
  • Cloud (SaaS e software)
  • On-Locale
  • kubernetes
  • docker
Casi d'uso tecnici
  • Sessioni ASP.NET
  • Sessioni ASP.NET Core
  • Messaggistica Pub/Sub
  • SignalR in tempo reale per ASP.NET
  • Internet of Things (IoT)
  • Database NoSQL
  • Streaming Processing
  • Microservices
Risorse
  • Articoli di riviste
  • Articoli di terze parti
  • Articoli
  • Video
  • Fogli bianchi
  • Spettacoli
  • trattativa
  • Blog
  • Docs
Casi di studio dei clienti
  • Testimonianze
  • Clienti
Assistenza
  • Pianificare un demo
  • Forum (Google Gruppi)
  • Consigli
Azienda
  • Leadership
  • Partner
  • News
  • Eventi
  • Lavora con noi
Contattaci

  • IngleseCinese (semplificato)FranceseTedescoItalianoGiapponeseCoreanoPortogheseCorsi

  • Contattaci
  •  
  • Mappa del sito
  •  
  • Termini d’uso
  •  
  • Informativa privacy
© Copyright Alachisoft 2002 - . Tutti i diritti riservati. NCache è un marchio registrato di Diyatech Corp.
Torna in alto