캐시에 기존 데이터 업데이트/삽입
NCache 제공 Insert
메서드 및 해당 오버로드를 사용하여 캐시에서 개체 업데이트를 용이하게 합니다. 기존 항목의 데이터를 덮어쓰는 동안 캐시에 키가 없으면 항목도 캐시에 추가합니다.
사전 조건
캐시의 개체 업데이트
주의 사항
이 기능은 다음에서도 사용할 수 있습니다. NCache Professional.
다양한 오버로드를 사용하여 캐시에서 사용자 정의 개체를 업데이트할 수 있습니다. Insert
방법. 이것은 CacheItemVersion
.
중대한
- 키가 이미 있는 경우 기존 캐시 항목을 동일한 키로 덮어씁니다.
- 키가 없으면 작업에서 캐시에 항목을 대신 추가합니다.
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
다음 예에서는 기존 개체의 값을 가져와 동일한 키에 대해 캐시에 삽입합니다. 키가 존재하지 않으면 캐시에 추가합니다.
// 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은 고유 키에 대해 캐시에서 업데이트됩니다.
중대한
- 키가 이미 있는 경우 기존 캐시 항목을 동일한 키로 덮어씁니다.
- 키가 없으면 작업에서 캐시에 항목을 대신 추가합니다.
다음 예에서는 기존 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의.
도 참조
.그물: Alachisoft.NCache.고객 네임 스페이스.
자바 : COM.alachisoft.ncache.고객 네임 스페이스.
Node.js : 캐시 클래스입니다.
파이썬 : ncache.고객 클래스입니다.