前段時間,一個圖片伺服器的磁碟IO隊列過高,原因是訪問量比較高,達到2500 req/s。webserver用的是IIS,磁碟是普通的SATA硬碟。為瞭解決此問題,想到了緩衝。緩衝解決方案有很多種,例如:SQUID、ASP.NET+memcached、ASP.NET頁面緩衝等等。簡單起見,我採用了ASP.NET頁面緩衝來實現。
話不多說,先上解釋具體的實現方法。
在項目裡新增一個imgcache.aspx頁面,頁面上設定頁面緩衝,暫時設為600秒。
<%@ OutputCache Duration="600" VaryByParam="path" %>
在上面這行裡應該看到path了吧,path即圖片的路徑。程式會讀取這個檔案進行緩衝起來,並且輸出到瀏覽器。
在imgcache.aspx.cs檔案裡,首頁擷取path的值,然後用FileStream讀取此檔案,再就是輸出到Response.OutputStream。
調用例子:http://image.xxxxxxx.com/imgcache.aspx?path=/images/defaultsingerhead.jpg
具體代碼如下:
imgcache.aspx.cs
using System;<br />using System.Collections.Generic;<br />using System.Linq;<br />using System.Web;<br />using System.Web.UI;<br />using System.Web.UI.WebControls;<br />using System.IO;<br />public partial class ImgCache : System.Web.UI.Page<br />{<br /> protected void Page_Load(object sender, EventArgs e)<br /> {<br /> string path = Request.QueryString["path"];<br /> if (string.IsNullOrEmpty(path) || !File.Exists(Server.MapPath(path)))<br /> {<br /> Response.StatusCode = 404;<br /> }<br /> else<br /> {<br /> FileStream myStream = new FileStream(Server.MapPath(path), FileMode.Open, FileAccess.Read, FileShare.Delete);<br /> myStream.Seek(0,SeekOrigin.Begin);<br /> byte[] data = Kugou.Util.Globals.StreamToBytes(myStream, 0, (int)myStream.Length);<br /> myStream.Close();<br /> Response.ContentType = "image/png";<br /> Response.OutputStream.Write(data, 0, data.Length);<br /> }<br /> }<br />}<br />
imgcache.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImgCache.aspx.cs" Inherits="ImgCache" %><br /><%@ OutputCache Duration="600" VaryByParam="path" %>
此方案最大的特點就是簡單,快速實現了緩衝圖片的功能。應用此方案之後,磁碟隊列很快就降下來了。
當然,此方案還不是很完美,存在以下不足:
1、不適合做分布式的緩衝,要是分布式的用Memcached會好很多;
2、輸出的圖片在瀏覽器端不緩衝,原因是使用ASP.NET服務端頁面緩衝後的http有問題,HTTP頭如下:
(Status-Line) HTTP/1.1 200 OK
Connection close
Date Tue, 13 Jul 2010 09:37:49 GMT
Server Microsoft-IIS/6.0
X-Powered-By ASP.NET
X-AspNet-Version 2.0.50727
Cache-Control public, max-age=307
Expires Tue, 13 Jul 2010 09:42:56 GMT
Last-Modified Tue, 13 Jul 2010 09:32:56 GMT
Vary *
Content-Type image/png
Content-Length 959
如果把OutputCache的Location屬性改成Client,就可以在瀏覽器端緩衝。<%@ OutputCache Duration="600" VaryByParam="path" Location="Client"%>。這樣改了之後輸出的HTTP頭如下:
(Status-Line) HTTP/1.1 200 OK
Connection close
Date Tue, 13 Jul 2010 09:44:15 GMT
Server Microsoft-IIS/6.0
X-Powered-By ASP.NET
X-AspNet-Version 2.0.50727
Cache-Control private, max-age=600
Expires Tue, 13 Jul 2010 09:54:15 GMT
Last-Modified Tue, 13 Jul 2010 09:44:15 GMT
Content-Type image/png
Content-Length 959
這兩個HTTP頭的差別在於,第一個多了行Vary *。還有Cache-Control的值不一樣。
使用了瀏覽器端緩衝之後,伺服器端就沒緩衝。Location屬性還有個值為ServerAndClient,設了之後瀏覽器不緩衝。可能是我愚見了。。
用Cache對象進行緩衝可以解決這個問題。以後再改了。