更新/插入缓存中的现有数据
NCache 提供 Insert
方法及其重载,以方便更新缓存中的对象。 虽然它会覆盖现有项目的数据,但如果缓存中不存在该键,它还会将该项目添加到缓存中。
先决条件
更新缓存中的对象
备注
此功能也可用于 NCache Professional.
您可以使用各种重载来更新缓存中的自定义对象 Insert
方法。 这会返回一个 CacheItemVersion
.
重要
- 如果 key 已经存在,它将用相同的 key 覆盖现有的缓存项。
- 如果该键不存在,则该操作将该项添加到缓存中。
备注
为确保操作是故障安全的,建议处理应用程序中的任何潜在异常,如中所述 处理故障.
以下示例获取现有对象的值,并将其根据相同的键插入到缓存中。 如果该键不存在,则将其添加到缓存中。
// Precondition: Cache is already connected
string customerKey = "ALFKI";
// Get updated product from database against given product ID
Customer customer = FetchProductFromDB("ALFKI");
// Insert Product object to cache
CacheItemVersion version = cache.Insert(customerKey, customer);
// Item updated in cache successfully
// Precondition: Cache is already connected
// Get updated product from database against given product ID
Product product = fetchProductFromDB(1001);
// Insert Product object to cache
CacheItemVersion version = cache.insert("1001", product);
// Item updated in cache successfully
// Precondition: Cache is already connected
// Get product from database against given product ID
product = await this.fetchProductFromDB();
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// insert Product object to cache
var version = await this.cache.insert(key, product);
// Item added in cache successfully
# 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()
# Insert Product object to cache
version = cache.insert(key, product)
# Item inserted in cache successfully
更新过期对象
备注
此功能也可用于 NCache Professional.
CacheItem
是由提供的自定义类 NCache 它可用于将数据添加到缓存,还允许您将与对象关联的附加规范设置为此类的属性。 CacheItem 根据唯一键在缓存中更新。
重要
- 如果 key 已经存在,它将用相同的 key 覆盖现有的缓存项。
- 如果该键不存在,则该操作将该项添加到缓存中。
下面的示例获取现有 CacheItem 的更新值并将其针对相同的键插入到缓存中。 如果该键不存在,则将其添加到缓存中。
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB("ALFKI");
// Update Customer's Phone
customer.Phone = "0921-12 34 65";
// Cretae CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
// Update cutsomer in DB and Cache
if (UpdateDB(customer))
{
cache.Insert(customerKey, cacheItem);
}
String customerKey = "ALFKI";
// Get the customer from the database
Customer customer = fetchCustomerFromDB(customerKey);
// Update Customer's Phone
customer.setPhone("0921-12 34 65");
// Create CacheItem
CacheItem cacheItem = new CacheItem(customer);
cacheItem.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));
// Update customer in DB and Cache
cache.insert(customerKey, cacheItem);
System.out.println("Customer updated in cache successfully");
// Get product from database against given product ID
product = await this.fetchProductFromDB();
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Create a new CacheItem for this product
// You can OPTIONALLY specify multiple properties e.g. Priority, Expiration
// These properties are explained in successive chapters
var cacheItem = new ncache.CacheItem(product);
// insert CacheItem to cache
var version = await this.cache.insert(key,cacheItem);
# 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
# You can OPTIONALLY specify multiple properties e.g.Priority, Expiration
# These properties are explained in successive chapters
cache_item = ncache.CacheItem(product)
# Insert CacheItem to cache
version = cache.insert(key, cache_item)
更新缓存中的批量项目
备注
此功能也可用于 NCache Professional.
InsertBulk
更新数组 CacheItem
到缓存中对应的键。 该方法返回一个包含所有更新失败的键的字典,以及失败的原因。
重要
如果任何密钥更新失败,其失败原因将作为 IDictionary
.
下面的代码示例获取一个产品数组( 对客户的 类型)从数据库中。 然后将产品作为键的字典插入到缓存中,然后 CacheItem
运用 InsertBulk
.
// Create an array of all Customer Keys
String[] keys = new String[]
{
"Customer:ALFKI", "Customer:ANATR", "Customer:ANTON", "Customer:AROUT", "Customer:BERGS"
};
// Get items from cache
IDictionary<string, Customer> itemsFetched = cache.GetBulk<Customer>(keys);
//Create a dictionary to store updated items
IDictionary<string, CacheItem> itemsUpdated = new Dictionary<string, CacheItem>();
// Update postal codes of dictionary items
foreach (KeyValuePair<string, Customer> item in itemsFetched)
{
//Update Postal Code
item.Value.PostalCode = "05023";
// Create CacheItem of updated Customer object
CacheItem updatedCacheItem = new CacheItem(item.Value);
// Add uCacheItem to dictionary
itemsUpdated.Add(item.Key,updatedCacheItem);
}
if (UpdateDB(itemsUpdated))
{
// Insert updated bulk items to Cache
IDictionary<string, Exception> keysFailedToInsert = cache.InsertBulk(itemsUpdated);
if (keysFailedToInsert.Count > 0)
{
foreach (KeyValuePair<string, Exception> keyFailedToInsert in keysFailedToInsert)
Console.WriteLine($"Could not update Item {keyFailedToInsert.Key} in cache due to error : {keyFailedToInsert.Value}");
}
}
// Create an array of all Customer Keys
List<String> keys = List.of(
"Customer:ALFKI",
"Customer:ANATR",
"Customer:ANTON",
"Customer:AROUT",
"Customer:BERGS"
);
// Get items from cache
Map<String, Customer> itemsFetched = cache.getBulk(keys, Customer.class);
//Create a dictionary to store updated items
Map<String, CacheItem> itemsUpdated = new HashMap<>();
// Update postal codes of dictionary items
for (Map.Entry<String, Customer> item : itemsFetched.entrySet()) {
//Update Postal Code
item.getValue().setPostalCode("05023");
// Create CacheItem of updated Customer object
CacheItem updatedCacheItem = new CacheItem(item.getValue());
// Add uCacheItem to dictionary
itemsUpdated.put(item.getKey(), updatedCacheItem);
}
if (updateDB(itemsUpdated)) {
// Insert updated bulk items to Cache
Map<String, Exception> keysFailedToInsert = cache.insertBulk(itemsUpdated);
if (keysFailedToInsert.size() > 0) {
for (Map.Entry<String, Exception> keyFailedToInsert : keysFailedToInsert.entrySet()) {
System.out.printf("Could not update Item %s in cache due to error : %s", keyFailedToInsert.getKey(), keyFailedToInsert.getValue());
}
}
}
// Fetch all products from database
var products = await this.fetchProductFromDB();
//Create map of items to be added to cache
var dictionary = new Map();
products.forEach(prod => {
var key = "Product:" + this.product.getProductID();
var cacheItem = new ncache.CacheItem(this.product);
//insert dictionary to cache
this.cache.insert(key,cacheItem);
});
var keysFailedToAdd = this.cache.addBulk(dictionary);
if(keysFailedToAdd.size() > 0)
{
keysFailedToAdd.forEach(entry => {
if(entry.getValue() == false)
{
var ex = false;
}
else
{
// Any other exception
}
});
}
# Fetch all products from database
products = fetch_products_from_db()
# Create map of items to be inserted to cache
dictionary = {}
for product in products:
key = "Product:" + product.get_product_id()
cache_item = ncache.CacheItem(product)
# Add items to dictionary
dictionary[key] = cache_item
keys_failed_to_insert = cache.insert_bulk(dictionary)
if len(keys_failed_to_insert) > 0:
for entry in keys_failed_to_insert:
if not keys_failed_to_insert[entry]:
value = False
else:
# Any other exception
value = True
使用异步 API 更新对象
InsertAsync
返回的对象 任务类 可以根据客户端应用的业务需求进一步使用。
string customerKey = $"Customer:ALFKI";
// Get customer from database if not found in cache
if (customer == null)
customer = FetchCustomerFromDB("ALFKI");
// Update customer's Phone
customer.Phone = "12345-6789";
// Update cutsomer in DB and Cache
if (UpdateDB(customer))
{
// Adding item asynchronously.
Task<CacheItemVersion> task = cache.InsertAsync(customerKey, customer);
// This task object can be used as per your business needs
if (task.IsCompleted)
{
// Get CacheItemVersion object from task result
CacheItemVersion version = task.Result;
Console.WriteLine($"Item {customer.CustomerID} has been updated with verion {version.Version}.");
}
}
String customerKey = "Customer:ALFKI";
// Get customer from database if not found in cache
if (customer == null)
Customer customer = fetchCustomerFromDB("Customer:ALFKI");
// Update customer's Phone
customer.setPhone("12345-6789");
// Update cutsomer in DB and Cache
if (updateDB(customer)) {
// Adding item asynchronously.
FutureTask<CacheItemVersion> task = cache.insertAsync(customerKey, customer);
// Wait for task to complete and get CacheItemVersion object from task result
CacheItemVersion version = task.get();
System.out.println("Item " + customer.getCustomerID() + " has been updated with version " + version.getVersion() + ".");
}
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product string
key = f"Product:{product.get_product_id()}"
# Insert Product object to cache asynchronously
async def insert_async():
task = cache. insert_async("key", "product")
value = await task
asyncio.run(insert_async())
# This task object can be used as per your business needs
更多资讯
NCache 提供了基本操作的示例应用程序 GitHub上.
参见
.NET: Alachisoft.NCache。客户 命名空间。
Java的: COM。alachisoft.ncache。客户 命名空间。
节点.js: 缓存 类。
Python: ncache。客户 类。