• Facebook
  • 트위터
  • 유튜브
  • 라인드인
  • RSS
  • 기술 문서
  • 비교
  • 블로그
  • 다운로드
  • 문의하기
다운로드
목차 표시/숨기기

Write-behind 사용

이 섹션에서는 쓰기 관통(Write-through) 공급자를 배포 및 구성한 후 쓰기 지연(Write-behind) 모드를 사용하는 방법을 설명합니다. 쓰기 지연 모드에서는 캐시 추가, 업데이트 및 삭제 작업이 즉시 완료되는 반면, 백엔드 데이터 소스 업데이트는 백그라운드에서 비동기적으로 수행됩니다. 쓰기 지연 모드는 단일 작업, 대량 작업 및 비동기 작업을 지원합니다. NCache 데이터 구조를 포함하며, 작업 알림을 수신하도록 콜백을 구성할 수 있습니다.

사전 조건

  • . NET
  • 레거시 API
  • 설치 Alachisoft.NCache.SDK 애플리케이션에 NuGet 패키지가 포함됩니다.
  • API를 활용하려면 애플리케이션에 다음 네임스페이스를 포함합니다.
    • Alachisoft.NCache.Runtime.DatasourceProviders
    • Alachisoft.NCache.실행 시간
    • Alachisoft.NCache.런타임.예외
    • Alachisoft.NCache.고객
  • 작업을 수행하기 전에 응용 프로그램이 캐시에 연결되어 있어야 합니다.
  • 캐시가 실행 중이어야 합니다.
  • 기본적으로 지원되지 않는 데이터 형식의 경우 뉴턴소프트사용자 정의를 구성합니다. JSON 변환기.
  • 추가되는 데이터가 직렬화 가능.
  • API 세부 정보는 다음을 참조하세요. 캐시 아이템, 돈을 받아가세요, 끼워 넣다, IWriteThruProvider, 제거, 삽입대량, 대량 제거, 삽입비동기, 비동기 제거, 쓰기 모드, 쓰기 옵션, SetDataSource 알림, 데이터 소스 수정된 콜백, 이벤트 유형.
  • .NET 클라이언트 애플리케이션에 다음 NuGet 패키지를 설치하세요.
    • 기업 : Install-Package Alachisoft.NCache.SDK -Version 4.9.1.0
  • 새로운 콘솔 애플리케이션을 만듭니다.
  • 추가되는 데이터가 직렬화 가능.
  • 추가 NCache 참고자료 위치를 찾아서 %NCHOME%\NCache\bin\assembly\4.0 추가 Alachisoft.NCache.Web Alachisoft.NCache.Runtime 적절한.
  • 포함시키다 Alachisoft.NCache.Runtime.DatasourceProviders Alachisoft.NCache.Web.Caching 애플리케이션의 네임스페이스.
  • 에 대한 자세한 내용을 보려면 NCache 레거시 API를 다운로드하세요 NCache 4.9 문서는 다음과 같이 사용 가능합니다. .지퍼 에 파일 Alachisoft 웹 사이트.

추가/업데이트

쓰기 지연 기능이 활성화된 상태에서도 콜백을 사용하거나 사용하지 않고 캐시 항목을 추가/업데이트할 수 있습니다. 콜백을 사용하여 항목을 추가하면 등록한 특정 이벤트에 대한 알림을 받게 됩니다.

콜백 메소드 없이 추가

다음 예제에서는 Write-behind가 활성화된 캐시에 항목을 추가합니다. Insert() 방법. 이 방법을 사용하면 항목이 이미 캐시에 있는 경우 새 값이 이전 값을 덮어씁니다.

  • . NET
  • 레거시 API
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
}
try
{
    // Precondition: Cache is already connected
    // Using NCache Enterprise 4.9.1

    Product product = FetchProductByProductID(1001);

    // Specify the key of the cacheItem
    string key =  $"Product:{product.ProductID}";
    CacheItem cacheItem = new CacheItem(product);

    // Add item in the cache with Write-Behind enabled
    cache.Insert(key, cacheItem, DSWriteOption.WriteBehind, null);
}
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 쓰기 뒤에 쓰기 기능이 활성화되어 있습니다.

  • . NET
  • 레거시 API
// 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);
// Using NCache Enterprise 4.9.1
// 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);

// Add item in the cache with Write-Behind and a data source callback
cache.Insert(key, cacheItem, DSWriteOption.WriteBehind, OnDataSourceItemsAdded);

기존 데이터 제거

아래 예에서, Remove 이 메서드는 Write-behind가 활성화된 상태에서 지정된 키와 연관된 항목을 제거하는 데 사용됩니다. 해당 항목은 캐시와 데이터 소스 모두에서 제거되고, 이 작업에 대한 관련 이벤트가 등록됩니다.

  • . NET
  • 레거시 API
// 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);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

// Specify the key of the item
string key = "Product:1001";

// Remove the item corresponding to the key with Write-behind enabled
Object returnObject = cache.Remove(key, DSWriteOption.WriteThru, null);

대량 작업

다음과 같이 Write-behind를 사용하여 대량 작업을 수행할 수 있습니다.

대량 항목 추가/업데이트

다음 예제에서는 Write-behind가 활성화된 캐시에 대량 항목을 추가합니다. InsertBulk() 방법. 항목이 이미 캐시에 있으면 새 값이 기존 값을 덮어씁니다.

  • . NET
  • 레거시 API
// 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);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

String[] key = { "Customer:David:1001", "Customer:Paul:1002", "Customer:Dave:1003", "Customer:Mathew:1004" };

// Create new  custom objects for above mentioned keys of Customer type
CacheItem[] data = GetCacheItems(key.Length);

IDictionary failedItems = cache.InsertBulk(key, data, DSWriteOption.WriteBehind, OnDataSourceItemsUpdated);

기존 항목 제거

다음 예제에서는 Write-behind가 활성화된 캐시에서 대량의 항목을 제거합니다. RemoveBulk() 방법.

  • . NET
  • 레거시 API
// 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);
// Using NCache Enterprise 4.9.1
// Precondition: Cache is already connected

// Fetch all products from the database
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++;
}

// Remove items with Write-behind enabled
IDictionary failedItems = cache.RemoveBulk(keys, DSWriteOption.WriteBehind, OnDataSourceItemsRemoved);
주의 사항

방법을 사용 OnDataSourceItemsRemoved() 캐시에서 데이터를 제거한 후 작업을 수행합니다.

비동기 작업

다음과 같이 Write-behind를 사용하여 비동기 작업을 수행할 수 있습니다.

항목 추가/업데이트

다음 예제에서는 Write-behind가 활성화된 캐시에 항목을 비동기적으로 추가합니다. InsertAsync() 방법.

  • . NET
  • 레거시 API
// 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);
// Using NCache Enterprise 4.9.1
// 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);

// Add Product object to cache
cache.InsertAsync(key, cacheItem, DSWriteOption.WriteBehind, OnDataSourceItemsUpdated);

항목 제거

다음 예제에서는 Write-behind가 활성화된 캐시에서 기존 항목을 비동기적으로 제거합니다. RemoveAsync() 방법.

  • . NET
// 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)이 활성화된 상태에서 서로 다른 데이터 구조를 사용합니다.

  • . NET
// 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.실행 시간 네임 스페이스.

문의하기

전화

+1 214-619-2601   (미국)

+44 20 7993 8327   (UK)

 
이메일

sales@alachisoft.com

support@alachisoft.com

NCache
  • 판 비교
  • NCache 아키텍처
  • 벤치 마크
다운로드
가격
놀이터를 사용해보십시오

배포
  • 클라우드(SaaS 및 소프트웨어)
  • 온 프레미스
  • Kubernetes
  • 도커
기술 사용 사례
  • ASP.NET 세션
  • ASP.NET 코어 세션
  • 게시/구독 메시징
  • 실시간 ASP.NET SignalR
  • 사물의 인터넷 IOT ()
  • NoSQL 데이터베이스
  • 스트림 처리
  • 마이크로 서비스
리소스
  • 잡지 기사
  • 제XNUMX자 기사
  • 기사
  • 비디오
  • 백서
  • 쇼
  • 회담
  • 블로그
  • 기술 문서
고객 사례 연구
  • 환자 후기
  • 고객
고객 지원
  • 데모 예약
  • 포럼(Google 그룹스)
  • Tips
회사
  • Leadership
  • 파트너
  • ​뉴스
  • 이벤트
  • 채용 정보
문의하기

  • 영어중국어 (간체)프랑스어독일 사람이탈리아 사람일본제한국어포르투갈어스페인어

  • 문의하기
  •  
  • 사이트 맵
  •  
  • 이용 약관
  •  
  • 개인정보 처리방침
© 저작권 Alachisoft 2002 - . 판권 소유. NCache 는 Diyatech Corp.의 등록상표입니다.
맨 위로