캐시에 데이터 추가
캐시에 성공적으로 연결하고 유효한 캐시 핸들을 얻은 후 캐시에 데이터를 추가할 수 있습니다. NCache 제공 Add
메서드 및 해당 오버로드를 사용하여 처음으로 캐시에 개체를 추가할 수 있습니다.
캐시에 데이터를 추가하기 위한 전제 조건
캐시에 개체 추가
주의 사항
이 기능은 다음에서도 사용할 수 있습니다. NCache Professional.
다양한 오버로드를 사용하여 사용자 지정 클래스의 개체를 캐시에 추가할 수 있습니다. Add
방법.
경고
키가 이미 존재하는 경우 "지정된 키가 이미 존재합니다." 예외가 발생합니다.
다음 예에서는 프로덕트 클래스 및 관련 키를 캐시에 저장합니다. 이것은 반환 CacheItemVersion
. 그런 다음 코드 샘플은 키가 캐시에 성공적으로 추가되었는지 여부를 확인합니다.
팁
항목이 추가되었는지 확인하는 빠른 방법 중 하나는 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 사용
다목적 특성으로 인해 추가 작업의 또 다른 광범위한 용도는 여러 응용 프로그램에서 캐시를 사용하는 경우 캐시를 잠그는 것입니다.
예를 들어, 애플리케이션이 캐시에 연결되자마자 모든 애플리케이션에 알려진 특정 키를 추가하도록 환경이 설정됩니다. 그리고 애플리케이션이 캐시 사용을 완료하면 캐시에서 키가 제거됩니다. 키가 성공적으로 추가되면 논리에 따라 캐시 사용을 계속할 수 있습니다. 그러나 키가 이미 존재하는 경우 이는 캐시가 이미 애플리케이션에서 사용 중이고 "잠겨" 있음을 의미합니다.
이것은 다음 다이어그램의 단계에서 설명됩니다.
앱 A와 앱 B는 애플리케이션이 시작되자마자 "WorkStarted" 키를 추가합니다.
App A에서 전달한 키는 App B에서 전달된 키보다 먼저 캐시에 추가됩니다.
앱 B에서는 "지정된 키가 이미 존재합니다." 예외가 발생합니다. 이 시나리오에서 App B는 App A가 작업을 완료할 때까지, 즉 "WorkStarted" 키를 성공적으로 추가할 수 있을 때까지 기다립니다.
앱 A는 작업이 완료되면 캐시에서 키를 제거합니다.
앱 B는 캐시에 키를 다시 추가합니다.
키는 App B에 의해 성공적으로 추가되어 다른 애플리케이션에 대한 캐시를 잠급니다.
추가 자료
NCache 기본 작업에 대한 샘플 응용 프로그램을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.고객 네임 스페이스.
자바 : COM.alachisoft.ncache.고객 네임 스페이스.
Node.js : 캐시 클래스입니다.
파이썬 : ncache.고객 클래스입니다.