将数据添加到缓存
在成功连接到缓存并获得有效的缓存句柄后,您可以将数据添加到缓存中。 NCache 提供 Add
方法及其重载,以方便首次将对象添加到缓存中。
将数据添加到缓存的先决条件
将对象添加到缓存
备注
此功能也可用于 NCache Professional.
您可以使用各种重载将自定义类的对象添加到缓存中 Add
方法。
警告
如果key已经存在,则会抛出“指定的key已存在”异常。
下面的例子添加了一个对象 产品 类及其关联的键进入缓存。 这返回 CacheItemVersion
. 代码示例然后检查密钥是否已成功添加到缓存中。
Tips:
验证是否已添加项目的一种快速方法是使用 Cache 类的以下任一属性:
Count
返回缓存中存在的项目数。
Contains
验证缓存中是否存在指定的键。
// Precondition: Cache is already connected
// Get customer from database
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// Get customer from database if not found in cache
if (customer == null)
{
// Get customer from database
customer = FetchCustomerFromDB("ALFKI");
cache.Add(customerKey, customer);
}
// Item added in cache successfully
// Pre-condition: Cache is already connected
String customerKey = "ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
// Get product from database against given product ID
if (customer == null) {
// Fetch customer from database
customer = fetchCustomerFromDB("ALFKI");
cache.insert(customerKey, customer);
}
// Item added in cache successfully
// This is an async method
// Pre-condition: Cache is already connected
// Get product from database against given product ID
product = await this.fetchProductFromDB(1001);
// Generate a unique cache key for this product
var key = "Product:" + product.getProductID();
// Add Product object to cache
var version = await this.cache.add(key, product);
// Item added in cache successfully
# Pre-condition: Cache is already connected
# Get product from database against given product ID
product = fetch_product_from_db(1001)
# Generate a unique cache key for this product
key = "Product:" + product.get_product_id()
# Add Product object to cache
version = cache.add(key, product)
# Item added in cache successfully
备注
为确保操作是故障安全的,建议处理应用程序中的任何潜在异常,如中所述 处理故障.
添加过期对象
备注
此功能也可用于 NCache Professional.
您可以通过将带有元数据的数据封装在缓存中来将其添加到缓存中 NCache CacheItem
类。
下面的例子添加了一个基本的 CacheItem
含 对客户的 对象进入缓存。 将针对 CacheItem
在后续章节中。
// Get customer from database if not found in cache
if (customer == null)
{
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
// You can use CacheItem object to add metadata along with data to cache
// CacheItem comprises of certain properties such as Expiration which are explained in successive chapters
CacheItem customerCacheItem = new CacheItem(customer);
customerCacheItem.Expiration = new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5));
cache.Add(customerKey, customerCacheItem);
}
String customerKey = "ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
if (customer == null) {
// Fetch customer from database
customer = fetchCustomerFromDB("ALFKI");
}
// Create a new CacheItem with the customer data
CacheItem customerCacheItem = new CacheItem(customer);
// Set the expiration for the CacheItem to 5 minutes sliding expiration
customerCacheItem.setExpiration(new Expiration(ExpirationType.Sliding, TimeSpan.FromMinutes(5)));
// Add the CacheItem to the cache
cache.insert(customerKey, customerCacheItem);
// Item added in cache successfully
System.out.println("Item added in cache with expiration successfully");
// This is an async method
// Get product from database against given product ID
product = await this.fetchProductFromDB(1001);
// 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);
// Add CacheItem to cache
var version = await this.cache.add(key,cacheItem);
# Get product from database against given product ID
product = fetch_product_from_db(1001)
# 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)
# Add CacheItem to cache
version = cache.add(key, cache_item)
except Exception as exp:
# Handle errors
添加批量项目以缓存数据
备注
此功能也可用于 NCache Professional.
AddBulk
添加一个数组 CacheItem
使用相应的缓存键到缓存。 此方法返回所有未能添加的键的字典以及失败原因。
备注
对于任何未能添加的密钥,失败原因将作为 IDictionary
.
以下代码将大量产品项添加到缓存中。 如果有密钥添加失败,可根据业务需求进行处理。
// 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, CacheItem> itemsFetched = cache.GetCacheItemBulk(keys);
// Fetch items from DB which do not exist in Cache
if (itemsFetched.Count < keys.Length)
{
//Create dictionary of items to be added to cache
IDictionary<string, CacheItem> missingItems = new Dictionary<string, CacheItem>();
foreach (string key in keys)
{
if (!itemsFetched.ContainsKey(key))
{
Customer customer = FetchCustomerFromDB(key);
CacheItem cacheItem = new CacheItem(customer);
missingItems.Add(key, cacheItem);
}
}
// Add bulk items to Cache
IDictionary<string, Exception> keysFailedToAdd = cache.AddBulk(missingItems);
if (keysFailedToAdd.Count > 0)
{
foreach( KeyValuePair<string,Exception> keyFailedToAdd in keysFailedToAdd)
Console.WriteLine($"Could not add Item {keyFailedToAdd.Key} in cache due to error : {keyFailedToAdd.Value}");
}
}
List<String> keys = List.of(
"Customer:ALFKI",
"Customer:ANATR",
"Customer:ANTON",
"Customer:AROUT",
"Customer:BERGS"
);
// Get items from cache
Map<String, CacheItem> itemsFetched = cache.getCacheItemBulk(keys);
// Fetch items from DB which do not exist in Cache
if (itemsFetched.size() < keys.size()) {
//Create dictionary of items to be added to cache
Map<String, CacheItem> missingItems = new HashMap<>();
for (String key : keys) {
if (!itemsFetched.containsKey(key)) {
Customer customer = fetchCustomerFromDB(key);
CacheItem cacheItem = new CacheItem(customer);
missingItems.put(key, cacheItem);
}
}
// Add bulk items to Cache
Map<String, Exception> keysFailedToAdd = cache.addBulk(missingItems);
if (keysFailedToAdd.size() > 0) {
for (Map.Entry<String, Exception> keyFailedToAdd : keysFailedToAdd.entrySet()) {
System.out.println("Could not add Item " + keyFailedToAdd.getKey() + " in cache due to error: " + keyFailedToAdd.getValue());
}
}
}
// This is an async method
// 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(prod);
//Add items to dictionary
dictionary.set(key,cacheItem);
});
var keysFailedToAdd = this.cache.addBulk(dictionary);
if(keysFailedToAdd.size() > 0)
{
keysFailedToAdd.forEach(entry => {
if(entry.getValue() == false)
{
var value = false;
}
else
{
// Any other exception
}
});
}
# Fetch all products from database
products = fetch_products_from_db()
# Create map of items to be added 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_add = cache.add_bulk(dictionary)
if len(keys_failed_to_add) > 0:
for entry in keys_failed_to_add:
if not keys_failed_to_add[entry]:
value = False
else:
# Any other exception
value = True
使用异步 API 添加对象
AddAsync
异步添加一个项目到缓存并返回一个对象 任务类 可以根据客户端应用的业务需求进一步使用。
if (customer == null)
{
string customerKey = $"Customer:ALFKI";
Customer customer = FetchCustomerFromDB(customerKey);
//Adding item asynchronously.You can also add data by creating a CacheItem object which stores meta data as well
Task<CacheItemVersion> task = cache.AddAsync(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 added to cache with verion {version.Version}.");
}
}
String customerKey = "Customer:ALFKI";
Customer customer = fetchCustomerFromDB(customerKey);
cache.addAsync(customerKey, customer).get();
# Get product from database
product = fetch_product_from_db()
# Generate a unique cache key for this product string
key = f"Product:1001"
# Add Product object to cache asynchronously
async def add_async():
task = cache.add_async("key", "product")
value = await task
asyncio.run(add_async())
# This task object can be used as per your business needs
使用 ICache.Add 进行分布式锁定
由于其多功能性,添加操作的另一个广泛用途是锁定缓存(如果多个应用程序正在使用该缓存)。
例如,设置一个环境,一旦任何应用程序连接到缓存,它就会添加所有应用程序都知道的特定密钥。 一旦应用程序使用完缓存,它就会从缓存中删除密钥。 如果key添加成功,就可以按照其逻辑继续使用缓存。 但是,如果该密钥已经存在,则意味着缓存已被应用程序使用并且被“锁定”。
这在下图中的步骤中进行了描述:
应用程序 A 和应用程序 B 在应用程序启动后立即添加“WorkStarted”键。
App A 传递的 key 在 App B 传递的 key 之前被添加到缓存中。
应用程序 B 收到“指定的密钥已存在”异常。 在这种情况下,应用程序 B 将等待应用程序 A 完成其工作,即直到它可以成功添加“WorkStarted”键。
应用程序 A 完成工作后从缓存中删除密钥。
App B 再次将密钥添加到缓存中。
App B 成功添加密钥,锁定其他应用程序的缓存。
更多资讯
NCache 提供基本操作的示例应用程序 GitHub上.
参见
.NET: Alachisoft.NCache。客户 命名空间。
Java的: COM。alachisoft.ncache。客户 命名空间。
节点.js: 缓存 类。
Python: ncache。客户 类。