캐시 로더 및 리프레셔 구현
캐시 시작 로더 및 리프레셔를 사용하려면 ICacheLoader
인터페이스를 먼저 구현해야 합니다. 그런 다음 Loader 및 Refresher의 사용자 정의 논리를 다음을 사용하여 구성할 수 있습니다. NCache 관리 센터 or 명령줄 도구. NCache 사용자 정의 논리를 기반으로 구성된 데이터 소스에서 데이터를 로드하고 새로 고칩니다. 캐시 시작 시, NCache 전화 Init
캐시 시작 로더의 메소드를 사용하여 초기화합니다. 캐시 시작 로더의 성공적인 초기화, 구현된 호출 LoadDatasetOnStartup
캐시에 데이터를 로드하는 방법입니다. 그런 다음 다음을 사용합니다. 새로 고침 데이터 세트 결정된 캐시에 로드된 데이터를 새로 고치는 방법 새로 고침 간격.
다음 예에서 클라이언트는 다음을 구현합니다. ICacheLoader
사용자 정의 로더 및 리프레셔 논리를 구성하는 인터페이스입니다. 두 개의 데이터 세트를 구성한 경우 NCache 관리 센터: 제품 및 공급 업체. 다음 구현 로드 제품 및 공급 업체 캐시 시작 시. 또한 지정된 새로 고침 시간 간격에 따라 이러한 데이터 세트를 새로 고칩니다.
캐시 로더의 구성 요소에 대한 자세한 내용은 챕터를 참조하십시오. 캐시 시작 로더 및 리프레셔의 구성요소.
캐시 로더 및 리프레셔 전제 조건
- 모든 작업에 필요한 표준 전제 조건에 대해 알아보려면 NCache 서버 측 기능은 다음 페이지를 참조하십시오. 서버 측 API 전제 조건.
- API 세부 정보는 다음을 참조하세요. 아이캐시, 캐시 아이템, ICacheLoader.
- 이것은 클래스 라이브러리 프로젝트여야 합니다.
- 에 있는지 확인 캐시 로더 구성 를 사용하여 NCache 관리 센터 또는 명령줄 도구 NCache 클러스터.
캐시 로더 및 리프레셔 초기화
다음 코드는 구현 방법을 보여줍니다 Init
방법 ICacheLoader
상호 작용. 이 방법은 매개변수를 입력으로 받아 이에 대한 값을 할당합니다.
public void Init(IDictionary<string, string> parameters, string cacheName)
{
cache = CacheManager.GetCache(cacheName);
connectionString = parameters.ContainsKey("ConnectionString") ? parameters["ConnectionString"] : null;
if (connectionString != null)
{
connection = new SqlConnection(connectionString);
}
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
캐시 시작 시 데이터 로드
다음 구현은 LoadDatasetOnStartup
메소드는 프로덕트 데이터 소스에서 가져와 캐시에 추가합니다. 그만큼 LoadDatasetOnStartup
캐시에 로드된 데이터에 대한 정보를 보유하는 사용자 컨텍스트를 반환합니다. 이 메서드는 캐시가 캐시에 데이터를 미리 로드하기 시작할 때 호출됩니다.
public object LoadDatasetOnStartup(string dataset)
{
// Create a list of datasets to load at cache startup
IList<object> datasetToLoad;
switch (dataset.ToLower())
{
// If dataset is products, fetch products from data source to load in cache
case "products":
datasetToLoad = FetchProductsFromDataSource();
// Insert fetched products in the cache
foreach (var product in datasetToLoad)
{
string key = $"ProductID:{product.Id}";
cache.Insert(key, product);
}
break;
// If dataset is suppliers, fetch suppliers from data source to load in cache
case "suppliers":
datasetToLoad = FetchSuppliersFromDataSource();
// Insert fetched suppliers in the cache
foreach (var supplier in datasetToLoad)
{
string key = $"SupplierID:{supplier.Id}";
cache.Insert(key, supplier);
}
break;
default:
// Invalid dataset
}
// User context is the time at which datasets were loaded in the cache
object userContext = DateTime.Now;
return userContext;
}
데이터세트 새로고침
다음 코드는 Cache Refresher가 호출될 때마다 시작 시 캐시에 로드된 데이터를 새로 고치는 방법을 구현합니다. 그만큼 새로 고침 데이터 세트 메서드는 에서 반환된 사용자 컨텍스트를 사용합니다. LoadDatasetOnStartup 새로 고칠 데이터를 확인하는 방법입니다.
public object RefreshDataset(string dataset, object userContext)
{
DateTime? lastRefreshTime;
switch (dataset.ToLower())
{
// If dataset is products, fetch updated products from data source
case "products":
lastRefreshTime = userContext as DateTime?;
IList<Product> productsToRefresh = FetchUpdatedProducts(lastRefreshTime) as IList<Product>;
// Insert updated products in the cache
foreach (var product in productsToRefresh)
{
string key = $"ProductID:{product.Id}";
CacheItem cacheItem = new CacheItem(product);
_cache.Insert(key, cacheItem);
}
break;
// If dataset is supplier, fetch updated suppliers from data source
case "suppliers":
lastRefreshTime = userContext as DateTime?;
IList<Supplier> suppliersToRefresh = FetchUpdatedSuppliers(lastRefreshTime) as IList<Supplier>;
// Insert updated suppliers in the cache
foreach (var supplier in suppliersToRefresh)
{
string key = $"SupplierID:{supplier.Id}";
CacheItem cacheItem = new CacheItem(supplier);
_cache.Insert(key, cacheItem);
}
break;
default:
// Invalid dataset
}
// User context is the time at which datasets were refreshed
userContext = DateTime.Now;
return userContext;
}
새로 고칠 데이터 세트 가져오기
XNUMXD덴탈의 새로고침할 데이터 집합 가져오기 메소드는 런타임에 사전 구성된 데이터세트를 새로 고치는 사용자 정의 로직을 구현합니다. RefreshPreference
. 이 메소드는 사용자 컨텍스트를 가져와서 새로 고침 기본 설정 지정된 데이터 세트에 따라 다릅니다.
public IDictionary<string, RefreshPreference> GetDatasetsToRefresh(IDictionary<string, object> userContexts)
{
DateTime? lastRefreshTime;
bool datasetHasUpdated;
// Create a dictionary for datasets to refresh with their Refresh Preference
IDictionary<string, RefreshPreference> DatasetsToRefresh = new Dictionary<string, RefreshPreference>();
foreach (var dataset in userContexts.Keys)
{
switch (dataset.ToLower())
{
// If dataset is products, check if dataset has been updated in data source
// if yes, then refresh the dataset now
case "products":
lastRefreshTime = userContexts[dataset] as DateTime?;
datasetHasUpdated = HasProductDatasetUpdated(dataset, lastRefreshTime);
if (datasetHasUpdated)
{
DatasetsToRefresh.Add(dataset, RefreshPreference.RefreshNow);
}
break;
// If dataset is suppliers, check if dataset has been updated in data source
// if yes, then refresh dataset on next time of day
case "suppliers":
lastRefreshTime = userContexts[dataset] as DateTime?;
datasetHasUpdated = HasSupplierDatasetUpdated(dataset, lastRefreshTime);
if (datasetHasUpdated)
{
DatasetsToRefresh.Add(dataset, RefreshPreference.RefreshOnNextTimeOfDay);
}
break;
default:
// Invalid dataset
}
}
// Return the dictionary containing datasets to refresh on polling with their refresh preferences
return DatasetsToRefresh;
}
모든 리소스 폐기
결국 전화를 Dispose
방법을 사용하면 낭비를 방지하기 위해 모든 리소스를 닫거나 삭제했는지 확인할 수 있습니다.
주의 사항
캐시 로더/새로 고침 구성 NCache 를 참조하여 캐시 로더 및 새로 고침 구성 도움말을 보려면 관리자 안내서를 참조하십시오.
추가 자료
NCache 캐시 로더 및 리프레셔에 대한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.실행 시간 네임 스페이스.
자바 : COM.alachisoft.ncache.runtime.cacheloader 네임 스페이스.