Dipendenza dei dati della cache dal file
La dipendenza dai file fornisce un meccanismo per invalidare i dati della cache in caso di origini dati non relazionali. Qui puoi associare una dipendenza file/cartella a un elemento di dati della cache. Ogni volta che il file/cartella viene rimosso o modificato, NCache rimuoverà l'elemento dipendente dalla cache. Il thread di pulizia della cache monitora ogni volta il file o la cartella dipendenti per eventuali modifiche CleanInterval
.
Nel thread di pulizia della cache, NCache attiva la dipendenza nei seguenti scenari:
- Il file di dipendenza viene rimosso/modificato.
- La cartella delle dipendenze viene rimossa/modificata.
- La dipendenza viene creata nel file/cartella inesistente, ma viene creata durante l'intervallo di pulizia.
Allo stesso modo, più elementi possono dipendere da un singolo file. Qualsiasi modifica in un file, tramite l'aggiornamento o l'eliminazione, fa sì che la cache rimuova gli elementi dipendenti dalla cache. Allo stesso modo, un elemento può creare una dipendenza da più file, in Dipendenza da file.
Puoi anche fornire un ritardo chiamato startAfter
in Dipendenza file che indica quando iniziare a monitorare il file dipendente per eventuali modifiche. In questo modo, NCache inizierà a controllare il file dipendente dopo il startAfter
tempo è trascorso.
Dipendenza dei dati della cache dai prerequisiti dei file
Consigli
Assicurarsi che il NCache Il servizio ha accesso al percorso del file in cui si trova il file da cui dipendere.
Aggiungi la dipendenza dai file con i dati della cache
CacheItem
è una classe personalizzata fornita da NCache che può essere utilizzato per aggiungere dati alla cache e consente anche di impostare metadati aggiuntivi associati a un oggetto di questa classe. Questi metadati definiscono le proprietà dell'elemento come dipendenze, scadenze e altro.
I Aggiungi Il metodo aggiunge un nuovo elemento nei dati della cache mentre il metodo inserire Il metodo aggiunge un nuovo elemento con dipendenza e, se l'elemento esiste già nella cache, sovrascrive le proprietà preesistenti.
Nell'esempio seguente, i dati aggiunti nella cache sono il contenuto del file posizionato nel percorso specificato come a CacheItem
con dipendenza dal file. Qualsiasi modifica nel file comporterà la scadenza dei dati dipendenti presenti nella cache. Gli elementi scaduti verranno quindi rimossi dalla cache CleanInterval
.
// Precondition: Cache is already connected
// Specify the file path to add dependency on the file
string filepath = "D:\\Products.csv";
// Getting product from file.
Product product = FetchProductFromFile(filepath);
string key = $"Product: {product.ProductID}";
// Create a new cacheItem with product data.
var cacheItem = new CacheItem(product);
// Create the dependency on the file with specified path.
cacheItem.Dependency = new FileDependency(filepath);
// Add the file data in the cache with dependency on the file
cache.Add(key, cacheItem);
// Precondition: Cache is already connected
// Specify the file path to add dependency on the file
String filepath = "D:\\Products.csv";
// Getting product from file.
Product product = fetchProductFromFile(filepath);
String key = "Product: " + product.getProductId();
// Create a new cacheItem with product data.
var cacheItem = new CacheItem(product);
// Create the dependency on the file with specified path.
cacheItem.setDependency(new FileDependency(filepath));
// Add the file data in the cache with dependency on the file
cache.add(key, cacheItem);
// Precondition: Cache is already connected
// Generate a unique key for the fileData
let key = "FileData";
let filePath = "test.txt";
// Get the content of the file as string
let fileData = this.cache.get(key, String.class);
let blob = new Blob;
// Read the contents of the file placed at the path
if (!(fileData == null)) {
var file = new FileReader();
file.readAsText(blob, filePath);
}
// Create a new cache item with the file data
let cacheItem = new ncache.CacheItem(fileData);
// Create File Dependency on the file placed at filePath
cacheItem.setDependency(new ncache.FileDependency(filePath));
// Add the file data in the cache with dependency on the file
this.cache.insert(key, cacheItem);
# Precondition: Cache is already connected
# Generate a unique key for the fileData
key = "FileData"
file_path = "Path/To/File"
# Get the content of the file as string
file_data = cache.get(key, str)
# Check if the file_data is already in the cache
if file_data is None or not file_data:
# Read the contents of the file placed at the path
file = open(file_path, mode='r')
file_data = file.read()
file.close()
# Create a new cache item with the file data
cache_item = ncache.CacheItem(file_data)
# Create File Dependency on the file placed at filePath
cache_item.set_dependency(ncache.FileDependency(file_path))
# Add the file data in the cache with dependency on the file
cache.insert(key, cache_item)
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.
Attiva la dipendenza dei file con ritardo
Se desideri aggiungere una dipendenza a un elemento che viene attivato dopo un determinato periodo di tempo, NCache consente di specificare l'intervallo di tempo per questo.
I Aggiungi il metodo aggiunge un nuovo elemento nella cache mentre il inserire Il metodo aggiunge un nuovo elemento con dipendenza e se l'elemento esiste già nella cache, ne sovrascrive le proprietà.
Nell'esempio seguente, i dati aggiunti nella cache sono il contenuto del file posizionato nel percorso specificato con dipendenza dal file. La dipendenza verrà attivata dopo un intervallo di 20 minuti. Qualsiasi modifica nel file comporterà la scadenza dei dati dipendenti presenti nella cache. Gli elementi scaduti verranno quindi rimossi dalla cache CleanInterval
.
// Specify the file path to add dependency on the file
string filepath = "D:\\Products.csv";
//Getting product from file.
Product product = FetchProductFromFile(filepath);
// Creating a unique key for product.
string key = $"Product: {product.ProductID}";
// Create a new cacheItem with product data.
var cacheItem = new CacheItem(product);
// Create the dependency on the file with specified path.
cacheItem.Dependency = new FileDependency(filepath, DateTime.Now.AddMinutes(20));
// Add the file data in the cache with dependency on the file
cache.Insert(key, cacheItem);
// Specify the file path to add dependency on the file
String filepath = "D:\\Products.csv";
//Getting product from file.
Product product = fetchProductFromFile(filepath);
// Creating a unique key for product.
String key = "Product: " + product.getProductId();
// Create a new cacheItem with product data.
var cacheItem = new CacheItem(product);
// Create the dependency on the file with specified path.
cacheItem.setDependency(new FileDependency(filepath, Date.from(Instant.ofEpochSecond(TimeSpan.FromMinutes(20)._ticks))));
// Add the file data in the cache with dependency on the file
cache.insert(key, cacheItem);
// Generate a unique key for the fileData
let key = "FileData";
let filePath = "test.txt";
// Get the content of the file as string
let fileData = this.cache.get(key, String.class);
let blob = new Blob;
// Read the contents of the file placed at the path
if (!(fileData == null)) {
var file = new FileReader();
file.readAsText(blob, filePath);
}
// Create a new cache item with the key
let cacheItem = new ncache.CacheItem(fileData);
// Create delay for dependency
let now = ncache.Calender.getInstance();
now.add(ncache.Calendar.MINUTE, 20);
let delayTime = now.getTime();
// Create File Dependency on the file placed at filePath
// The dependency starts after 20 minutes
cacheItem.setDependency(new ncache.FileDependency(filePath, delayTime));
// Add the file data in the cache with dependency on the file
this.cache.insert(key, cacheItem);
# Generate a unique key for the fileData
key = "FileData"
# Specify the file path to add dependency on the file
file_path = "Path/To/File"
# Get the content of the file as string
file_data = cache.get(key, str)
# Check if the file_data is already in the cache
if file_data is None or not file_data:
# Read the contents of the file placed at the path
file = open(file_path, mode='r')
file_data = file.read()
file.close()
# Create a new CacheItem with the file_data
cache_item = ncache.CacheItem(file_data)
# Create the dependency on the file on the specified path
# The dependency starts after 20 minutes
cache_item.set_dependency(ncache.FileDependency(file_path, datetime.now() + timedelta(minutes=20)))
cache.insert(key, cache_item)
Aggiungi la dipendenza dei file su più file
È inoltre possibile aggiungere la dipendenza file a un elemento che dipende da più file o cartelle. In questo modo un singolo elemento può dipendere da più elementi utilizzando il file Aggiungi or inserire metodo. Il Add
il metodo aggiunge un nuovo elemento nella cache mentre il Insert
aggiunge un nuovo elemento con dipendenza e se l'elemento esiste già nella cache ne sovrascrive le proprietà.
L'esempio seguente aggiunge un elemento con una chiave che dipende da due file inseriti nei percorsi specificati.
// Specify the file paths to add dependency on the file
string orderFilePath = "D:\\Orders.csv";
string orderDetailFilePath = "D:\\OrderDetail.csv";
string[] filePaths = { orderFilePath, orderDetailFilePath };
// Getting order from file.
Order order = FetchOrderFromFile(orderFilePath);
string key = $"Order: {order.OrderID}";
// Create a new cacheItem with order data.
var cacheItem = new CacheItem(order);
// Create the dependency on the files with specified path.
cacheItem.Dependency = new FileDependency(filePaths);
// Add the file data in the cache with dependency on the files.
cache.Add(key, cacheItem);
// Specify the file paths to add dependency on the file
String orderFilePath = "D:\\Orders.csv";
String orderDetailFilePath = "D:\\OrderDetail.csv";
ArrayList<String> paths = new ArrayList<>(){};
paths.add(orderFilePath);
paths.add(orderDetailFilePath );
// Create the dependency on the files with specified paths.
FileDependency fileDependency = new FileDependency(paths);
// Getting customer from file.
Order order = fetchOrderFromFile(orderFilePath);
// Creating a unique key for the customer.
String key = "Order:" + order.getOrderDate();
// Create a new cacheItem with customer data.
CacheItem cacheItem = new CacheItem(order);
// Create the dependency on the files with specified path.
cacheItem.setDependency(fileDependency);
// Add the file data to the cache with dependency on the files.
cache.insert(key, cacheItem);
// Get product from database against productId
let product = this.fetchProductFromDb(this.productId);
// Create a unique cache key for this product
let key = "Product:" + product.ProductID;
// Create a new cache item
let cacheItem = new ncache.CacheItem(product);
// SPecify paths of the master files
// Make sure that the network file paths are accessible by NCache Service
let fileNames = ["\\fileserver1\\ProductList.csv", "\\fileserver1\\OrderList.csv"];
// Adding File Dependency on the specified cache item
cacheItem.setDependency(new ncache.FileDependency(fileNames));
// Insert the cache item with File Dependency
this.cache.insert(key, cacheItem);
// For successful addition of item with dependency
// Update or remove the file
# Get product from database against productId
product = fetch_product_from_db("1001")
# Create a unique cache key for this product
key = "Product:" + product.get_product_id()
# Create a new cache item
cache_item = ncache.CacheItem(product)
# Specify paths of the master files
# Make sure that the network file paths are accessible by NCache Service
file_names = ["\\fileserver1\\ProductList.csv", "\\fileserver1\\OrderList.csv"]
# Adding File Dependency on the specified cache item
cache_item.set_dependency(ncache.FileDependency(file_names))
# Insert the cache item with File Dependency
cache.insert(key, cache_item)
# For successful addition of item with dependency
# Update or remove the file
Aggiungi la dipendenza del file agli elementi della cache esistenti
NCache offre inoltre la facilità di aggiungere una dipendenza dalla chiave a un elemento già presente nella cache, senza reinserirlo nella cache.
Consigli
Questo approccio è relativamente meno leggero e più economico poiché gli elementi sono già presenti nella cache.
Utilizzo dell'API UpdateAttributes
Questo viene fatto attraverso il CacheItemAttribute
classe, che ha la proprietà di Dependency
da contrapporre CacheItem
. L'attributo viene quindi impostato rispetto alla chiave esistente dell'elemento, utilizzando il metodo UpdateAttributes
metodo del ICache
interfaccia.
L'esempio seguente aggiunge un elemento alla cache senza dipendenza e quindi imposta la dipendenza file per l'elemento utilizzando il metodo UpdateAttributes
metodo. Ciò non richiede la necessità di aggiungere nuovamente l'elemento alla cache.
// Precondition: Cache is already connected
// Specify the file path to add dependency on the file
string filepath = "D:\\Products.csv";
string key = $"Product: 1";
// Create a new cacheItemAttribute.
var attribute = new CacheItemAttributes();
// Create the dependency on the file with specified path.
attribute.Dependency = new FileDependency(filepath);
// update the cacheItem.
cache.UpdateAttributes(key, attribute);
// Specify the file path to add dependency on the file
String filepath = "D:\\Products.csv";
String key = "Product: 1";
// Create a new cacheItemAttribute.
CacheItemAttributes attribute = new CacheItemAttributes();
// Create the dependency on the file with specified path.
attribute.setDependency(new FileDependency(filepath));
// Update the cacheItem attributes.
cache.updateAttributes(key, attribute);
System.out.println("Cache item with key " + key + " updated with file dependency.");
// Generate a unique cache key for file data
let key = "FileData";
// Get the content of the file as string
// Make sure that the item already exists in the cache
let fileData = this.cache.get(key, String.class);
// Specify the filepath
let filePath = "\\FileHost\\ProductList.csp";
// Create a File Dependency where key is dependent on the file placed at filePath
var dependency = new ncache.FileDependency(filePath);
// Create a cache item attribute for dependency
var attribute = new ncache.CacheItemAttributes();
attribute.setDependency(dependency);
// Set the attributes of dependency against the existing cache key
this.cache.updateAttributes(key, attribute);
// Monitor/Verify dependency through PerfMon Counters or Cache API
# Generate a unique cache key for file data
key = "FileData"
# Specify the filepath
file_path = "\\FileHost\\ProductList.csp"
# Create a File Dependency where key is dependent on the file placed at file_path
dependency = ncache.FileDependency(file_path)
# Create a cache item attribute for dependency
attribute = ncache.CacheItemAttributes()
attribute.set_dependency(dependency)
# Set the attributes of dependency against the existing cache key
cache.update_attributes(key, attribute)
# Monitor / Verify dependency through PerfMon Counters or Cache API
Risorse addizionali
NCache fornisce un'applicazione di esempio per Dipendenza file su GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Dipendenze.di.runtime spazio dei nomi. spazio dei nomi.
Giava: com.alachisoft.ncache.dipendenze.di.runtime spazio dei nomi.
Node.js: Dipendenza da file classe.
Pitone: ncache.dipendenze.di.runtime classe.