asp.net

[.net] Global.asax 기반의 데이터 캐싱 및 테이블 바인딩 처리

TTTGGG 2024. 8. 22. 16:11
728x90
반응형
SMALL

.NET Framework 4.5에서 작업함

Application["CachedData"]에 데이터베이스에서 조회한 내용을 메모리에 저장
여러 클라이언트가 같은 데이터를 요청할 때마다 데이터베이스를 반복적으로 조회하지 않도록 함
이 데이터는 모든 사용자와 모든 세션에 걸쳐 공유됨
여러 사용자가 동시에 페이지를 열 때, 각 사용자는 Application["CachedData"]에 
저장된 동일한 데이터를 받음 

// Global.asax 

private static Container _container; // 전역 Container 필드 추가

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Initialize and register dependencies
    _container = new Container(); // Container 인스턴스 생성
    RegisterDependencies(_container); 

    // 데이터 캐싱을 시작합니다.
    CacheData();

    // 1초마다 데이터 갱신 
    System.Timers.Timer timer = new System.Timers.Timer(1000);
    timer.Elapsed += (sender, e) => CacheData();
    timer.Start();
}

private void CacheData()
{
    try
    {
        // 서비스에서 데이터를 가져와 Application에 저장
        using (var scope = AsyncScopedLifestyle.BeginScope(_container))
        {
            var testDispService = scope.GetInstance<TestService>();
            var data = testService.GetTestAsync().Result; // 데이터베이스에서 조회한 데이터를 저장
            Application["CachedData"] = data;
        }
    }
    catch (Exception ex)
    {
        // 예외 처리 로직 추가 가능 (예: 로그 기록)
    }
}

 

// 컨트롤러

[HttpPost]
[Route("GetTest")]
public async Task<ActionResult> GetTestAsync()
{
    try
    {
        // Global.asax에서 캐싱한 데이터를 비동기적으로 가져옵니다.
        var cachedData = HttpContext.Application["CachedtData"] as IEnumerable<TestDto>;

        if (cachedData == null)
        {
            // 캐시된 데이터가 없으면 서비스에서 데이터를 가져옵니다.
            var list = await _TestService.GetTestAsync();

            // 데이터베이스에서 가져온 데이터를 캐싱합니다.
            HttpContext.Application["CachedtData"] = list;

            // 클라이언트에게 데이터를 반환
            return Json(new { data = list });
        }

        // 캐시된 데이터를 클라이언트에게 반환
        return Json(new { data = cachedData });
    }
    catch (Exception ex)
    {
        return new HttpStatusCodeResult(500, "Internal server error");
    }
}

 

// 컨트롤러에 접근하는 스크립트

<script>
    function updateDashboard() {
        $.ajax({
            url: '/Test/GetTest',
            method: 'POST',
            success: function (response) {
				// 성공 시 처리
            },
            error: function () {
                console.error("Failed to fetch data");
                // 서버 오류 발생 시 처리 (예: 'Error' 표시)
                $('#grd tbody').append('<tr><td colspan="9">Error loading data</td></tr>');
            }
        });
    }

    // 1초마다 업데이트
    setInterval(updateDashboard, 1000);

    // 초기 로드 시에도 데이터를 불러옵니다.
    updateDashboard();
</script>
728x90
반응형
LIST