1. 程式人生 > >NancyFx 2.0的開源框架的使用-Caching

NancyFx 2.0的開源框架的使用-Caching

http obj manage flush pri pan 存儲 ice img

新建一個空的Web項目,命名CachingDemo

技術分享

技術分享

然後添加三個Nuget安裝包

  • Nancy
  • Nancy.Hosting.Aspnet
  • Nancy.ViewsEngines.Razor

技術分享

然後往項目裏面添加Models,Module,Views三個文件夾

技術分享

再往Models文件夾裏面添加CachingExtensions文件夾

技術分享

然後往CachingExtensions文件夾裏面添加ContextExtensions類

 public static class ContextExtensions
    {
        
public const string OUTPUT_CACHE_TIME_KEY = "OUTPUT_CACHE_TIME"; //啟用此路由的輸出緩存 public static void EnableOutputCache(this NancyContext context,int seconds) { context.Items[OUTPUT_CACHE_TIME_KEY]=seconds; } //禁用此路由的輸出緩存 public static void
DisableOutputCache(this NancyContext context) { context.Items.Remove(OUTPUT_CACHE_TIME_KEY); } }

技術分享

再往Models文件夾裏面添加CachedResponse類

        //在緩存的響應中封裝常規響應
        //緩存的響應調用舊的響應並將其存儲為字符串。
        //顯然, 這只適用於基於 ascii 文本的響應, 所以不要使用此
        //在實際應用中:-)
        private
readonly Response response; public CachedResponse(Response response) { this.response = response; this.ContentType = response.ContentType; this.Headers = response.Headers; this.Contents = this.GetContents(); } public override Task PreExecute(NancyContext context) { //return base.PreExecute(context); return this.response.PreExecute(context); } private Action<Stream> GetContents() { return stream => { using (var memoryStream = new MemoryStream()) { this.response.Contents.Invoke(memoryStream); var contents = Encoding.ASCII.GetString(memoryStream.GetBuffer()); var writer = new StreamWriter(stream) { AutoFlush = true }; writer.Write(contents); } }; }

技術分享

然後往Module文件夾裏面添加MainModule類

public MainModule()
        {
            Get("/",Lexan=>
            {
                return View["index.cshtml",DateTime.Now.ToString()];
            });
            Get("/cached",Lexan=>
            {
                this.Context.EnableOutputCache(30);
                return View["Payload.cshtml",DateTime.Now.ToString()];
            });
            Get("/uncached",Lexan=>
            {
                this.Context.DisableOutputCache();
                return View["Payload.cshtml",DateTime.Now.ToString()];
            });
        }

技術分享

繼續往根目錄添加Bootstrapper類

        private const int CACHE_SECONDS = 30;
        private readonly Dictionary<string, Tuple<DateTime, Response, int>> cachedResponses = new Dictionary<string, Tuple<DateTime, Response, int>>();
        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            pipelines.BeforeRequest += CheckCache;
            pipelines.AfterRequest += SetCache;
        }
        //檢查我們是否有緩存條目-如果我們做了, 看看它是否已經過期,
        //如果沒有返回, 否則返回 null;
        public Response CheckCache(NancyContext context)
        {
            Tuple<DateTime, Response, int> cacheEntry;
            if (this.cachedResponses.TryGetValue(context.Request.Path,out cacheEntry))
            {
                if (cacheEntry.Item1.AddSeconds(cacheEntry.Item3)>DateTime.Now)
                {
                    return cacheEntry.Item2;
                }
            }
            return null;
        }
        //如果需要, 將當前響應添加到緩存中
        //僅按路徑存儲, 並將響應存儲在字典中。
        //不要將此作為實際緩存:-)
        public void SetCache(NancyContext contexts)
        {
            if (contexts.Response.StatusCode!=HttpStatusCode.OK)
            {
                return;
            }
            object cacheSecondsObject;
            if (!contexts.Items.TryGetValue(ContextExtensions.OUTPUT_CACHE_TIME_KEY,out cacheSecondsObject))
            {
                return;
            }
            int cacheSeconds;
            if (!int.TryParse(cacheSecondsObject.ToString(),out cacheSeconds))
            {
                return;
            }
            var cachedResponse = new CachedResponse(contexts.Response);
            this.cachedResponses[contexts.Request.Path]=new Tuple<DateTime, Response, int>(DateTime.Now,cachedResponse,cacheSeconds);
            contexts.Response = cachedResponse;
        }

技術分享

然後往Views文件夾裏面添加index,payload,兩個視圖

index頁面

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>首頁</title>
</head>
<body>
    <div>
    <h1>緩存Demo</h1>
        <p><a href="/cached">Cached頁面</a></p>
        <p><a href="/uncached">Uncached頁面</a></p>
    </div>
</body>
</html>

技術分享

Payload頁面

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>首頁</title>
</head>
<body>
    <div>
    <h1>緩存Demo</h1>
        <p>此頁是在: @Model</p>
        <p>這可能是或可能不會被緩存</p>
        <a href="/">主頁</a>
    </div>
</body>
</html>

技術分享

修改Web.config配置文件

    <httpHandlers>
      <add verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <add name="Nancy" verb="*" type="Nancy.Hosting.Aspnet.NancyHttpRequestHandler" path="*" />
    </handlers>
  </system.webServer>

技術分享

然後運行一下項目F5

技術分享

技術分享

謝謝你的欣賞,如有不對請多多指教!

NancyFx 2.0的開源框架的使用-Caching