2010-02-23 6 views
1

1 일 동안 캐싱을 수행하려고합니다. 내 MVC 모델에서 데이터베이스에서 데이터를 가져오고 내 뷰에서이 데이터를 사용하고 있습니다. 거기에 데이터가 없다면 캐시에 데이터를 추가하고 싶습니다. 캐시에 이미 있으면 직접 결과를 얻는 것이 좋습니다. 내 모델에서 나는 점에서 나는MVC에서 캐싱을 수행하는 방법

if (HttpContext.Current.Cache[ID] == null) 
{ 
    query = db.Employee.FirstOrDefault(x=>x.id.Equals(ID)); 
      HttpContext.Current.Cache.Insert 
      (ID, query, null,DateTime.Now.AddDays(1), 
       System.Web.Caching.Cache.NoSlidingExpiration); 
} else query = (Employee)HttpContext.Current.Cache[ID]; 

으로 캐싱을 사용했다 그러나 여기 캐싱은 현재 요청에서만 작동하고 다시 데이터가 데이터베이스에서 자궁강과 후 새로운 삽입은 캐시에서 수행) (함수 결과를 동일한 데이터에 대해 나는 1 일 동안 캐시에 데이터를 원한다. 내 데이터를 캐시하는 방법을 알려주십시오.

감사합니다.

+0

HttpContext.Current.Cache [ "ID"] HttpContext.Current.Cache [ID] (첫 번째 줄)를 의미합니까? 그렇지 않으면 코드에서 오류가 발생합니다. –

+0

예. HttpContext.Current.Cache [ID] –

답변

-1

가능한 경우 - cache ViewResults. 더 쉽고 더 좋습니다. 원 캐싱

, 내가 이것을 사용하고 있는데 예상대로 (여러 요청을 건너) 작동 =>

public static class CacheManager 
    { 
     public static bool Exists 
      (string cacheKey, HttpContextBase context) 
     { 
      return context.Cache[cacheKey] != null; 
     } 

     public static object Get 
      (string cacheKey, HttpContextBase context) 
     { 
      return context.Cache[cacheKey]; 
     } 

     public static T Get<T> 
      (string cacheKey, HttpContextBase context) 
      where T : class 
     { 
      return context.Cache.Get(cacheKey) as T; 
     } 

     public static T Get<T> 
      (string cacheKey, HttpContextBase context, Func<T> getItemCallback) 
      where T : class 
     { 
      T item = Get<T>(cacheKey, context); 
      if (item == null) { 
       item = getItemCallback(); 
       //by default - caching for 1 day 
       if (item!=null) 
        context.Cache.Insert(cacheKey, item, null, 
         DateTime.Now.AddDays(1),TimeSpan.Zero); 
      } 

      return item; 
     } 

     public static void Save<T> 
      (string cacheKey, HttpContextBase context, T value) 
      where T : class 
     { 
      context.Cache.Insert(cacheKey, value); 
     } 
    } 

사용 =>

public IList<Database> AllDatabases 
     { 
      get 
      { 
       return CacheManager.Get 
        (CacheKeys.AllDatabases, ControllerContext.HttpContext, 
        () => databaseRepository.GetAll()); 
      } 
     } 

만 - 나는 통과 믿고 상황에 맞는 기본이다 불필요한 복잡성.

1

작업의 전체 출력을 캐시 하시겠습니까, 아니면 단지 데이터베이스 쿼리입니까?

는이 경우과 같이 당신의 행동에 OutputCache를 속성을 사용

[OutputCache(Duration = 86400, VaryByParam = "None")] 
public ActionResult Index() 
{ 
    var data = GetFromDatabase(); 
    return View(data); 
} 

86400 우리는 24 시간을 캐시 할 것을 의미한다.

전체보기를 캐시하므로 모든 사용자가 동일한보기로 표시됩니다. 사용자 별 콘텐츠가있는 경우 댓글을 남기면 새로운 솔루션을 제공하려고 노력할 것입니다.

+0

작업의 출력을 캐시하지 않고 데이터베이스 쿼리 결과 만 캐시하고 싶습니다. –

관련 문제