Write-behind 사용
이 섹션에서는 쓰기 관통(Write-through) 공급자를 배포 및 구성한 후 쓰기 지연(Write-behind) 모드를 사용하는 방법을 설명합니다. 쓰기 지연 모드에서는 캐시 추가, 업데이트 및 삭제 작업이 즉시 완료되는 반면, 백엔드 데이터 소스 업데이트는 백그라운드에서 비동기적으로 수행됩니다. 쓰기 지연 모드는 단일 작업, 대량 작업 및 비동기 작업을 지원합니다. NCache 데이터 구조를 포함하며, 작업 알림을 수신하도록 콜백을 구성할 수 있습니다.
사전 조건
- 설치 Alachisoft.NCache.SDK 애플리케이션에 NuGet 패키지가 포함됩니다.
- API를 활용하려면 애플리케이션에 다음 네임스페이스를 포함합니다.
- 작업을 수행하기 전에 응용 프로그램이 캐시에 연결되어 있어야 합니다.
- 캐시가 실행 중이어야 합니다.
- 기본적으로 지원되지 않는 데이터 형식의 경우 뉴턴소프트사용자 정의를 구성합니다. JSON 변환기.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 캐시 아이템, 돈을 받아가세요, 끼워 넣다, IWriteThruProvider, 제거, 삽입대량, 대량 제거, 삽입비동기, 비동기 제거, 쓰기 모드, 쓰기 옵션, SetDataSource 알림, 데이터 소스 수정된 콜백, 이벤트 유형.
추가/업데이트
쓰기 지연 기능이 활성화된 상태에서도 콜백을 사용하거나 사용하지 않고 캐시 항목을 추가/업데이트할 수 있습니다. 콜백을 사용하여 항목을 추가하면 등록한 특정 이벤트에 대한 알림을 받게 됩니다.
콜백 메소드 없이 추가
다음 예제에서는 Write-behind가 활성화된 캐시에 항목을 추가합니다. Insert() 방법. 이 방법을 사용하면 항목이 이미 캐시에 있는 경우 새 값이 이전 값을 덮어씁니다.
try
{
// Precondition: Cache is already connected
Product product = FetchProductByProductID(1001);
// Specify the key of the cacheItem
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);
// Enable write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
// Add item in the cache with Write-behind
cache.Insert(key, cacheItem, writeThruOptions);
}
catch (OperationFailedException ex)
{
if (ex.ErrorCode == NCacheErrorCodes.BACKING_SOURCE_NOT_AVAILABLE)
{
// Backing source is not available
}
else if (ex.ErrorCode == NCacheErrorCodes.SYNCHRONIZATION_WITH_DATASOURCE_FAILED)
{
// Synchronization of data with backing source is failed due to any error
}
else
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
}
catch (Exception ex)
{
// Any generic exception like ArgumentNullException or ArgumentException
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
콜백 메소드로 추가
다음 예제는 콜백이 등록되고 이벤트 유형이 다음과 같은 항목을 캐시에 추가합니다. ItemAdded 쓰기 뒤에 쓰기 기능이 활성화되어 있습니다.
// Precondition: Cache is already connected
// Specify the key of the cacheItem
Product product = FetchProductByProductID(1001);
string key = $"Product:{product.ProductID}";
// Create a cache item
var cacheItem = new CacheItem(product);
// Enable write-behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
// Add item in the cache with Write-behind
cache.Insert(key, cacheItem, writeThruOptions);
기존 데이터 제거
아래 예에서, Remove 이 메서드는 Write-behind가 활성화된 상태에서 지정된 키와 연관된 항목을 제거하는 데 사용됩니다. 해당 항목은 캐시와 데이터 소스 모두에서 제거되고, 이 작업에 대한 관련 이벤트가 등록됩니다.
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";
// Enable write-through for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Remove the item corresponding to the key with Write-behind enabled
cache.Remove(key, DSWriteOption.WriteThru, null);
대량 작업
다음과 같이 Write-behind를 사용하여 대량 작업을 수행할 수 있습니다.
대량 항목 추가/업데이트
다음 예제에서는 Write-behind가 활성화된 캐시에 대량 항목을 추가합니다. InsertBulk() 방법. 항목이 이미 캐시에 있으면 새 값이 기존 값을 덮어씁니다.
// Precondition: Cache is already connected
// Fetch all products from database
Product[] products = FetchProductsFromDB();
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemUpdated);
IDictionary<string, CacheItem> dictionary = new Dictionary<string, CacheItem>();
foreach(var product in products)
{
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);
dictionary.Add(key, cacheItem);
}
IDictionary<string, Exception> keysFailedToUpdate = cache.InsertBulk(dictionary, writeThruOptions);
기존 항목 제거
다음 예제에서는 Write-behind가 활성화된 캐시에서 대량의 항목을 제거합니다. RemoveBulk() 방법.
// Precondition: Cache is already connected
// Get Keys
Product[] products = FetchProductsFromDB();
// Specify keys to remove from cache
string[] keys = new string[products.Length];
int index = 0;
foreach (var product in products)
{
keys[index] = $"Product:{product.ProductID}";
index++;
}
// Create dictionary to store removed items
IDictionary<string, Product> removedItems = new Dictionary<string,Product>();
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Remove items with Write-behind enabled
cache.RemoveBulk(keys, out removedItems, writeThruOptions);
주의 사항
방법을 사용 OnDataSourceItemsRemoved() 캐시에서 데이터를 제거한 후 작업을 수행합니다.
비동기 작업
다음과 같이 Write-behind를 사용하여 비동기 작업을 수행할 수 있습니다.
항목 추가/업데이트
다음 예제에서는 Write-behind가 활성화된 캐시에 항목을 비동기적으로 추가합니다. InsertAsync() 방법.
// Precondition: Cache is already connected
// Get product from database against given product ID
Product product = FetchProductFromDB(1001);
// Generate a unique cache key for this product
string key = $"Product:{product.ProductID}";
var cacheItem = new CacheItem(product);
// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemAdded);
// Add Product object to cache
Task task = cache.InsertAsync(key, cacheItem, writeThruOptions);
항목 제거
다음 예제에서는 Write-behind가 활성화된 캐시에서 기존 항목을 비동기적으로 제거합니다. RemoveAsync() 방법.
// Precondition: Cache is already connected
// Unique cache key of product to remove
string key = "Product:1001";
// Enable write behind for the cacheItem created
var writeThruOptions = new WriteThruOptions();
writeThruOptions.Mode = WriteMode.WriteBehind;
writeThruOptions.SetDataSourceNotification(DataSourceModifiedCallBack, EventType.ItemRemoved);
// Asynchronously remove items from cache
Task<Product> task = cache.RemoveAsync<Product>(key, writeThruOptions);
데이터 구조 사용
다음 예제는 지정된 항목에 대해 쓰기 지연(Write-behind)이 활성화된 상태에서 서로 다른 데이터 구조를 사용합니다.
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected
// Specify the key of the item
string key = "Product:1001";
var dataTypeAttributes = new DataTypeAttributes();
var writeThruOptions = new WriteThruOptions(WriteMode.WriteBehind, WriteThruProviderName);
switch(mainMenu)
{
case mainMenu.GetDistributedCounter:
// Modify or add count of the corresponding item with write behind enabled
var distributedCounter = cache.DataTypeManager.CreateCounter("counter", dataTypeAttributes, 0, writeThruOptions);
// Perform operations on counter
break;
case mainMenu.GetDistributedDictionary:
// Modify or add dictionary of the corresponding item with write thru enabled
var distributedDictionary = cache.DataTypeManager.CreateDictionary<string, int>(key, dataTypeAttributes, writeThruOptions);
// Perform operations on dictionary
break;
case mainMenu.GetDistributedList:
// Modify or add the list of the corresponding item with write behind enabled
var distributedList = cache.DataTypeManager.CreateList<int>("list", dataTypeAttributes, writeThruOptions);
// Perform operations on list
break;
case mainMenu.GetDistributedQueue:
// Modify or add the queue of the corresponding item with Read-through enabled
var distributedQueue = cache.DataTypeManager.CreateQueue<int>("queue", dataTypeAttributes, writeThruOptions);
// Perform operations on queue
break;
case mainMenu.GetDistributedHashSet:
// Modify or add the HashSet of the corresponding item with Read-through enabled
var distributedHashSet = cache.DataTypeManager.CreateHashSet<int>("hashset", dataTypeAttributes, writeThruOptions);
// Perform operations on hashset
break;
}
추가 자료
NCache Write-behind에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.실행 시간 네임 스페이스.