Dependência de dados de cache no arquivo
A Dependência de Arquivo fornece um mecanismo para invalidar os dados do cache no caso de fontes de dados não relacionais. Aqui você pode associar uma dependência de arquivo/pasta a um item de dados de cache. Sempre que esse arquivo/pasta for removido ou modificado, NCache removerá seu item dependente do cache. O thread de limpeza de cache monitora o arquivo/pasta dependente em busca de qualquer alteração a cada CleanInterval
.
No tópico de limpeza de cache, NCache desencadeia dependência nos seguintes cenários:
- O arquivo de dependência é removido/modificado.
- A pasta de dependência é removida/modificada.
- A dependência é criada no arquivo/pasta inexistente, mas no intervalo de limpeza ela é criada.
Da mesma forma, vários itens podem depender de um único arquivo. Qualquer alteração em um arquivo, seja por atualização ou exclusão, faz com que o cache remova os itens dependentes do cache. Da mesma forma, um item pode criar dependência de vários arquivos, em Dependência de Arquivo.
Você também pode fornecer um atraso chamado startAfter
em Dependência de Arquivo, que indica quando começar a monitorar o arquivo dependente em busca de qualquer alteração. Desta maneira, NCache começará a verificar o arquivo dependente após o startAfter
o tempo passou.
Dependência de dados de cache em pré-requisitos de arquivo
importante
Certifique-se de que o NCache O serviço tem acesso ao caminho do arquivo onde o arquivo do qual depende está colocado.
Adicionar dependência de arquivo com dados de cache
CacheItem
é uma classe personalizada fornecida por NCache que pode ser usado para adicionar dados ao cache e também permite definir metadados adicionais associados a um objeto desta classe. Esses metadados definem as propriedades do item, como dependências, expirações e muito mais.
A Adicionar método adiciona um novo item nos dados do cache, enquanto o método inserção O método adiciona um novo item com dependência e, se o item já existir no cache, ele sobrescreve as propriedades pré-existentes.
No exemplo a seguir, os dados adicionados no cache são o conteúdo do arquivo colocado no caminho especificado como CacheItem
com dependência do arquivo. Qualquer alteração no arquivo resultará na expiração dos dados dependentes presentes no cache. Os itens expirados serão removidos do 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
Para garantir que a operação seja à prova de falhas, é recomendável lidar com possíveis exceções em seu aplicativo, conforme explicado em Como lidar com falhas.
Acionar dependência de arquivo com atraso
Se você quiser adicionar uma dependência a um item que é acionado após um determinado período, NCache permite especificar o intervalo de tempo para isso.
A Adicionar adiciona um novo item no cache enquanto o método inserção O método adiciona um novo item com dependência e se o item já existir no cache, ele sobrescreve suas propriedades.
No exemplo a seguir, os dados adicionados ao cache são o conteúdo do arquivo colocado no caminho especificado com dependência do arquivo. A dependência será acionada após um período de 20 minutos. Qualquer alteração no arquivo resultará na expiração dos dados dependentes presentes no cache. Os itens expirados serão removidos do 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)
Adicionar dependência de arquivo em vários arquivos
Você também pode adicionar Dependência de Arquivo a um item que depende de vários arquivos ou pastas. Dessa forma, um único item pode depender de vários itens usando o método Adicionar or inserção método. o Add
adiciona um novo item no cache enquanto o método Insert
O método adiciona um novo item com dependência e se o item já existir no cache ele sobrescreve suas propriedades.
O exemplo a seguir adiciona um item com uma chave que depende de dois arquivos colocados nos caminhos especificados.
// 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
Adicionar dependência de arquivo a itens de cache existentes
NCache também oferece a facilidade de adicionar dependência de chave a um item já presente no cache, sem inseri-lo novamente no cache.
importante
Essa abordagem é comparativamente menos leve e mais econômica, pois os itens já estão presentes no cache.
Usando a API UpdateAttributes
Isso é feito por meio do CacheItemAttribute
classe, que tem a propriedade de Dependency
ser contra CacheItem
. O atributo é então definido em relação à chave existente do item, usando o método UpdateAttributes
método do ICache
interface.
O exemplo a seguir adiciona um item ao cache sem dependência e, em seguida, define a Dependência de Arquivo para o item usando o método UpdateAttributes
método. Isso não requer a necessidade de adicionar o item novamente ao 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
Recursos adicionais
NCache fornece aplicativo de amostra para dependência de arquivo em GitHub.
Veja também
.INTERNET: Alachisoft.NCache.Runtime.Dependências espaço para nome. espaço para nome.
Java: com.alachisoft.ncache.runtime.dependencies espaço para nome.
Node.js: Dependência de arquivo classe.
Pitão: ncache.runtime.dependencies classe.