캐시의 동작 및 사용 나열
분산 리스트는 순서가 지정된 데이터 구조로, 리스트에 데이터를 추가하거나 삭제할 수 있습니다. 예를 들어, 리스트는 전자상거래 웹사이트에서 사용자가 장바구니에 담은 상품 목록을 관리하는 데 사용됩니다. 사용자가 우산, 청사과, 커피와 같은 상품을 장바구니에 담았다고 가정해 보겠습니다. 결제를 진행하기 전에 청사과를 삭제하고 배를 추가할 수 있습니다. 이는 리스트의 어느 인덱스에서든 성능 저하 없이 업데이트가 가능하기 때문입니다.
NCache 다음을 제공하여 목록 데이터 구조를 더욱 향상시킵니다. NCache-다음과 같은 특정 기능 그룹, 태그, 만료, 잠금, 종속성그 외에도 여러 가지가 있습니다. 이 시나리오에서 회사는 세션이 활성화되어 있는 동안에만 장바구니 목록을 유지하기를 원합니다. 따라서 생성된 각 목록에 세션 시간 초과 값과 동일한 만료 시간을 설정할 수 있습니다.
NCache 목록 동작 및 제한 사항
이후 NCache 리스트는 동적 확장을 위해 설계되었으며, 대규모 데이터 세트를 분산 메모리 공간에 저장하면서도 인덱스 기반의 빠른 접근이 가능합니다.
- 목록은 모든 기본 유형 또는 사용자 정의 개체일 수 있습니다.
- 목록
CacheItem중첩 목록은 아직 지원되지 않습니다. - 목록은 인덱스로 직접 액세스할 수 있습니다.
- 리스트는 이름으로 지정됩니다. 따라서 각 리스트에 대해 고유한 캐시 키를 제공해야 합니다.
- null 값은 지원되지 않습니다.
- 중복 값이 지원됩니다.
사전 조건
사용하기 전에 NCache 클라이언트 측 API를 사용할 때 다음 전제 조건을 충족하는지 확인하십시오.
- .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
- 기업: Alachisoft.NCache.SDK
- 오픈 소스: Alachisoft.NCache오픈소스 SDK
- 애플리케이션에 다음 네임스페이스를 포함합니다.
- 캐시가 실행 중이어야 합니다.
- 추가되는 데이터가 직렬화 가능.
- API 세부 정보는 다음을 참조하세요. 아이캐시, IDistributedList, IDataTypeManager, 목록 만들기, 추가 범위, 머리에 삽입, 목록 가져오기, 범위 제거, 등록 알림, 데이터 유형 데이터 알림 콜백, 이벤트 유형, 데이터 유형 이벤트 데이터 필터, 로크, 자물쇠를 열다, 데이터 유형 관리자, 데이터 유형 이벤트 인수.
분산 리스트를 만들고 데이터를 추가하는 방법
CreateList 이 기능을 통해 애플리케이션은 만료 또는 제거와 같은 자동 데이터 무효화 정책을 지원하는 전용 분산 컬렉션을 생성할 수 있습니다.
다음 코드 샘플은 프로덕트 유형은 다음을 사용하여 캐시에 생성될 수 있습니다. CreateList 캐시 키에 대해 상품 목록. 제품은 다음을 사용하여 목록에 추가됩니다. Add, 다음을 사용하여 새로운 범위의 제품이 목록에 추가됩니다. AddRange.
팁
당신은 또한 수 검색 가능한 속성 구성 그룹/태그/명명된 태그와 같은 무효화 속성 데이터 구조를 생성하는 동안 만료/퇴거/종속성과 같은.
try
{
// Precondition: Cache is already connected
// Specify unique cache key for list
string key = "ProductList";
// Create list of Product type
IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);
// Get products to add to list
Product[] products = FetchProducts();
foreach (var product in products)
{
// Add products to list
list.Add(product);
}
// Get new products
Product[] newProducts = FetchNewProducts();
// Append list of new Products to existing list
list.AddRange(newProducts);
}
catch (OperationFailedException ex)
{
// NCache specific exception
if(ex.ErrorCode == NCacheErrorCodes.KEY_ALREADY_EXISTS)
{
// The specified key already exists in cache,
// Either remove the existing object from cache
// Or specify another key
}
else if (ex.ErrorCode == NCacheErrorCodes.CACHEITEM_IN_DATA_STRUCTURES)
{
// Data structures cannot be of CacheItem type
// CacheItems cannot be added in data structures
}
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
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
분산 리스트의 항목을 업데이트하는 방법
인덱스를 사용하여 리스트와 리스트의 항목을 업데이트할 수 있습니다. 리스트는 인덱스로 접근할 수 있기 때문입니다. 다음 코드 예제는 인덱스를 사용하여 기존 리스트(이전 예제에서 생성됨)의 값을 업데이트합니다. 그런 다음 할인 항목을 가져와 리스트의 첫 번째 인덱스에 추가합니다. InsertAtHead.
// Precondition: Cache is already connected
// "list" is created in the previous example
// Update value of index with updated product
Product updatedProduct = GetUpdatedProductByID(11);
list[11] = updatedProduct;
// Get product on sale to insert at the head of the list
Product saleProduct = FetchSaleItem();
list.InsertAtHead(saleProduct);
캐시에서 목록을 가져오는 방법
다음을 사용하여 캐시에서 목록을 가져올 수 있습니다. GetList이 함수는 캐시 키를 매개변수로 받습니다. 이 키는 목록 생성 시 지정한 목록의 이름입니다.
경고
가져오는 항목이 목록 유형이 아닌 경우 Type mismatch 예외가 발생합니다.
// Precondition: Cache is already connected
// List with this key already exists in cache
string key = "ProductList";
// Get the list and iterate through its items
IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);
if (retrievedList != null)
{
foreach (var item in retrievedList)
{
// Perform operations
}
}
else
{
// List does not exist
}
목록에서 항목을 제거하는 방법
팁
캐시에서 전체 목록을 제거하려면 다음을 참조하세요. 캐시에서 데이터 구조 제거 페이지를 확인하시기 바랍니다.
개별 항목 또는 지정된 항목 범위를 목록에서 제거할 수 있습니다. 다음 코드 샘플은 다음을 사용하여 개별 항목을 제거합니다. Remove 그리고 유통기한이 지난 다양한 제품들을 사용하여 RemoveRange.
주의 사항
제거할 키가 존재하지 않으면 아무것도 반환되지 않습니다. 반환된 항목 수는 반환 유형을 통해 확인할 수 있습니다. RemoveRange.
// Precondition: Cache is already connected
// List with this key already exists in cache
string key = "ProductList";
// Get list to remove items
IDistributedList<Product> retrievedList = cache.DataTypeManager.GetList<Product>(key);
// Get a range of out-of-stock products to be removed
List<Product> outOfStockProducts = FetchOutOfStockProducts();
// Remove each item individually from retrievedList
foreach(Product prod in outOfStockProducts)
{
retrievedList.Remove(prod);
}
// Get range of discontinued products to be removed
List<Product> discontinuedProducts = FetchDiscontinuedProducts();
// Remove this range from retrievedList
// Number of keys removed is returned
int itemsRemoved = retrievedList.RemoveRange(discontinuedProducts);
메일링 리스트에 이벤트 알림을 등록하는 방법
목록과 같은 데이터 구조에 캐시 이벤트, 키 기반 이벤트 및 데이터 구조 이벤트를 등록할 수 있습니다. 동작에 대해서는 다음을 참조하십시오. 기능별 동작.
다음은 레지스터에 대한 코드 샘플입니다. ItemAdded, ItemUpdated예산 및 ItemRemoved 리스트의 데이터 구조 관련 이벤트. 리스트를 생성하면 이벤트가 발생합니다. ItemAdded 캐시 레벨 이벤트입니다. 기존 목록에 항목을 추가하면 이 이벤트가 발생합니다. ItemAdded 데이터 구조 이벤트 및 ItemUpdated 캐시 레벨 이벤트. DataTypeEventDataFilter 데이터 구조 이벤트와 함께 반환되는 데이터의 양을 지정합니다.
생성된 목록에 이벤트를 등록하는 방법
// Precondition: Cache is already connected
// Unique cache key for list
string key = "ProductList";
// Create a list of Product type
IDistributedList<Product> list = cache.DataTypeManager.CreateList<Product>(key);
// Register ItemAdded, ItemUpdated, ItemRemoved events on list created
// DataTypeNotificationCallback is callback method specified
list.RegisterNotification(DataTypeDataNotificationCallback, EventType.ItemAdded |
EventType.ItemUpdated | EventType.ItemRemoved,
DataTypeEventDataFilter.Data);
// Perform operations
이벤트 알림에 대한 콜백 함수 지정 방법
private void DataTypeDataNotificationCallback(string collectionName, DataTypeEventArg collectionEventArgs)
{
switch (collectionEventArgs.EventType)
{
case EventType.ItemAdded:
// Item has been added to the collection
break;
case EventType.ItemUpdated:
if (collectionEventArgs.CollectionItem != null)
{
// Item has been updated in the collection
// Perform operations
}
break;
case EventType.ItemRemoved:
// Item has been removed from the collection
break;
}
}
리스트에 분산 잠금을 구현하는 방법
데이터 일관성을 보장하기 위해 목록을 명시적으로 잠그거나 잠금 해제할 수 있습니다. 다음 코드 샘플은 목록을 만들고 다음을 사용하여 10초 동안 잠급니다. 로크, 다음을 사용하여 잠금을 해제합니다. 자물쇠를 열다.
// Precondition: Cache is already connected
// List exists with key "ProductList"
string key = "ProductList";
// Get list
IDistributedList<Product> list = cache.DataTypeManager.GetList<Product>(key);
// Lock list for 10 seconds
bool isLocked = list.Lock(TimeSpan.FromSeconds(10));
if (isLocked)
{
// List is successfully locked for 10 seconds
// Unless explicitly unlocked
}
else
{
// List is not locked because either:
// List is not present in the cache
// List is already locked
}
list.Unlock();
추가 자료
NCache 목록 데이터 구조에 대한 샘플 응용 프로그램을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.클라이언트.데이터 유형 네임 스페이스.
자바 : com.alachisoft.ncache.client.데이터 구조 네임 스페이스.
Node.js : 분산 목록 클래스입니다.