CreateOutputCachedItemKey 緩存key的創建
2024-07-10 12:41:12
供稿:網友
有關OutputCache的相關資料大家可以查看 OutputCacheProvider OutputCache的一點點認識 ,我們還是復習一下OutputCache內容,OutputCache 的處理是在OutputCacheModule類中注冊ResolveRequestCache、UpdateRequestCache這2個方法,一個 用于獲取一個用于設置緩存。緩存內容分為兩部分,一部分為緩存策略CachedVary,一部分為緩存數據CachedRawResponse,一個頁面 緩存策略只有一個CachedVary,但是它卻可以有多個緩存內容CachedRawResponse。緩存內容的獲取和設置主要是依賴于HttpResponse的GetSnapshot() UseSnapshot(HttpRawResponse rawResponse, bool sendBody)方法。一般我們的緩 存都是要占用存儲空間的盡量減少緩存內容的副本是非常重要的,那么我們現在就來看看緩存key是如何創建的,key的創建取決于 CreateOutputCachedItemKey方法。CreateOutputCachedItemKey方法的內容還是比較復雜的,現在讓我們一 起來看看它的具體實現吧。
CreateOutputCachedItemKey方法又是如何調用的了,創建緩存策略key的代碼:this.CreateOutputCachedItemKey(context, null);創建緩存key的代碼:this.CreateOutputCachedItemKey(context, cachedVary)區別就在于參數CachedVary 的值一個為null,一個是真正的CachedVary 實例。我這里的代碼是通過Reflector.exe反編譯得到,感覺和真實的代碼有點差別,不過邏輯上是一樣的。
我還是以一個實際的例子來變解析邊說明,我這里是用asp.net mvc建立的一個demo。請求url:http://localhost:7503/Home/index 那么path就應該是:Home/index
首先我們的可以需要區分我們的請求是Get還是Post,Post以a1打頭,否則已a2打頭,緊接著追加當前的Path:
代碼如下:
if (verb == HttpVerb.POST)
{
builder = new StringBuilder("a1", path.Length + "a1".Length);
}
else
{
builder = new StringBuilder("a2", path.Length + "a2".Length);
}
builder.Append(CultureInfo.InvariantCulture.TextInfo.ToLower(path));
到這個時候我們的緩存策略key及確定的,我這里的策略key為:a2/home/index
如果我們的cachedVary不為null則繼續執行:
代碼如下:
for (int i = 0; i <= 2; i++)
{
int num;
string[] array = null;
NameValueCollection serverVarsWithoutDemand = null;
bool flag = false;
switch (i)
{
case 0:
builder.Append("H");
array = cachedVary._headers;
if (array != null)
{
serverVarsWithoutDemand = request.GetServerVarsWithoutDemand();
}
break;
case 1:
builder.Append("Q");
array = cachedVary._params;
if (request.HasQueryString && ((array != null) || cachedVary._varyByAllParams))
{
serverVarsWithoutDemand = request.QueryString;
flag = cachedVary._varyByAllParams;
}
break;
default:
builder.Append("F");
if (verb == HttpVerb.POST)
{
array = cachedVary._params;
if (request.HasForm && ((array != null) || cachedVary._varyByAllParams))
{