緩存的作用
要解決的問題
緩存哪些文檔?
域名 說明 Date 原始服務器產生響應的日期,中間的代理和緩存一定不能修改這個日期 Age 當代理服務器用自己緩存的副本響應請求時,用該頭部域表明該副本從產生到現在經過多長時間了。文檔經過代理時,Age首部值會隨之增加 Expires 指定響應資源的過期日期,表示在這個時間之前都是有效的 Cache-Control 有很多參數,看下面 :max-age=<s> 定義文檔的最大使用期 :no-store 資源不能被持久化保存起來(可以放入緩存),只能存在於內存中。用於防止敏感性的數據被複制。 :no-cache 不能被緩存起來。 :must-revalidate 每次在使用副本時,都要和源服務器進行驗證確定是否爲最新數據。 :private 數據資源只能被存儲到私有的caches中,即不能存儲在中間緩存服務器中 :public 數據資源可以在任何地方緩存起來 Last-Modified 資源文檔最後被修改的日期 Etag 與資源文檔關聯的一個值,類似於資源文檔的MD5值
緩存多久?
int freshness_limit ()
{
int heuristic , server_freshness_limit, time_since_last_modified ;
heuristic = 0;
if (Max_Age_value_set )
{
server_freshness_limit = Max_Age_value ;
}
else if ( Expire_value_set)
{
server_freshness_limit = Expire_value - Date_value;
}
else if ( Last_Modified_value_set)
{
time_since_last_modified = max (0, Date_value - Last_Modified_value);
server_freshness_limit = int ( time_since_last_modified* lm_factor );
heuristic = 1;
}
else
{
server_freshness_limit = default_cache_min_lifetime ;
heuristic = 1;
}
if (heuristic )
{
if (server_freshness_limit > default_cache_max_lifetime)
server_freshness_limit = default_cache_max_lifetime ;
else if ( server_freshness_limit < default_cache_min_lifetime )
server_freshness_limit = default_cache_min_lifetime ;
}
return 0;
}
LM-Factor算法
如果響應中沒有Cache-Control: max-age首部,也沒有Expires首部使用,就計算出一個試探性最大使用期。
time_since_modify = max(0, server_Date - server_Last_Modified);
server_freshness_limit = int(time_since_modify * lm_factor);
怎樣確定緩存的副本是有效的?
文檔使用期
int age ( int time_got_response, int Date_header_value , int Age_header_value)
{
int time_issued_request , current_time;
/* 修正時鐘偏差造成的負數使用期 */
int apparent_age = max(0, time_got_response - Date_header_value );
/* 修正時鐘偏差,取最保守的值 */
int corrected_apparent_age = max( apparent_age, Age_header_value );
/* 對網絡時延的補償 */
int response_delay_estimate = ( time_got_response - time_issued_request );
int age_when_document_arrived_at_our_cache = corrected_apparent_age + response_delay_estimate ;
int how_long_copy_has_been_in_our_cache = current_time - time_got_response ;
int age = age_when_document_arrived_at_our_cache + how_long_copy_has_been_in_our_cache ;
return age ;
}