ASP.NET Core 세션 사용
NCache 공통 IDistributedCache 인터페이스 구현을 통해 ASP.NET Core 세션과의 통합을 제공합니다. NCache 기존 코드를 변경하지 않고도 분산 세션 저장소를 구현할 수 있습니다. 세션 상태를 분산 저장소에 저장하는 것은 가능합니다. NCache 클러스터는 웹 팜에서 세션의 지속성, 확장성 및 높은 가용성을 보장합니다.
자세한 내용은 IDistributedCache 방법, 살펴보다 그들의 문서.
사전 조건
ASP.NET Core 세션을 사용하기 전에 NCache다음 전제 조건이 충족되었는지 확인하십시오.
- 다음 NuGet 패키지를 애플리케이션에 설치하십시오. NCache 판:
- 기업 : AspNetCore.세션.NCache
- 오픈소스: AspNetCore.세션.NCache.오픈소스
- 확장을 활용하려면 애플리케이션에 다음 네임스페이스를 포함하십시오.
- 캐시가 실행 중이어야 합니다.
- API 세부 정보는 다음을 참조하세요. 추가NCache세션, NCache세션.
- 추가되는 데이터가 직렬화 가능.
ASP.NET Core 세션을 사용하여 단일 캐시 구현
다음 코드 샘플은 캐시 키를 찾습니다. 캐시 키를 찾으면 결과를 포함하는 뷰를 반환합니다. 찾지 못하면 해당 캐시 키와 그에 상응하는 캐시 항목을 추가하고 캐시 항목의 슬라이딩 만료 시간을 30분으로 설정합니다. ASP.NET Core 세션을 사용하려면 업데이트하십시오. 홈 컨트롤러.cs 귀하의 신청서는 다음과 같습니다.
// Constructor injection for the IDistributedCache interface
public class HomeController : Controller
{
private IDistributedCache _cache;
public HomeController(IDistributedCache Cache)
{
// NCache is the underlying distributed provider
_cache = Cache;
}
public IActionResult CacheOperations()
{
try
{
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
object retrieveObj = _cache.Get(cacheKey);
if (retrieveObj != null)
{
// Return view with result
return View();
}
else
{
cacheEntry = DateTime.MaxValue;
var cacheEntryOptions = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30)
};
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
return View(cacheEntry);
}
}
catch (Exception ex)
{
// Handle error (log, fallback, etc.)
// Example: return fallback view or error page
return StatusCode(500, $"Cache error: {ex.Message}");
}
}
}
주의 사항
작업이 안전하도록 하려면 에 설명된 대로 응용 프로그램 내에서 잠재적인 예외를 처리하는 것이 좋습니다. 처리 실패.
ASP.NET Core 세션을 사용하여 여러 캐시 관리하기
ASP.NET Core 세션에서 여러 캐시를 사용하려면 설정을 수정하세요. 홈 컨트롤러.cs 사용 IDistributedCacheFactory특정 캐시 구성에 따라 세션 관리를 위한 동적 캐시 선택이 가능합니다.
public class HomeController : Controller
{
private IDistributedCacheFactory _cache;
public HomeController(IDistributedCacheFactory cacheFactory)
{
// Underlying cache is NCache
_cache = cacheFactory.GetDistributedCache("demoClusteredCache");
}
public IActionResult CacheOperations()
{
try
{
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
object retrieveObj = _cache.Get(cacheKey);
if (retrieveObj != null)
{
// Return view with result
return View();
}
else
{
cacheEntry = DateTime.MaxValue;
var cacheEntryOptions = new DistributedCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(30)
};
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
return View(cacheEntry);
}
}
catch (Exception ex)
{
// Log error here if needed
return StatusCode(500, $"Cache error: {ex.Message}");
}
}
}
추가 자료
NCache 세션 캐싱을 위한 샘플 애플리케이션을 제공합니다. GitHub의.
도 참조
.그물: Alachisoft.NCache.캐싱.분산 네임 스페이스.