亚洲必赢手机入口数码筛选和API优化,NET中数量缓存和输出缓存详解

by admin on 2019年10月2日

筛选数据

必要:假如数据库中留存OrderNum相同,且IsDefault差异的笔录,那么IsDefault值为0的记录将替换值为1的记录(IsDefault值为1的笔录不呈现)。

亚洲必赢手机入口 1

由于查出来的数目相当少,100条以内,所以作者是一贯全体查询到List内存中,然后在内部存款和储蓄器中开展多少过滤的操作,思来想去都觉着作者如下的完毕格局很low,不过本身时期又没悟出好的主意,不理解大家有未有好的法门?

            var newList = list.ToList();
            //筛选出哪些排序号有重复
            var orderNumList = newList.GroupBy(g => g.OrderNum).Select(g => new { orderNum = g.Key, count = g.Count() }).Where(g => g.count > 1).Select(s => s.orderNum).ToList();
            var cfList = newList.Where(w => orderNumList.Contains(w.OrderNum)); //获取有重复排序号的记录

            var cfDefaultList = cfList.Where(w => w.IsDefault);  //默认模块记录
            var cfNoDefaultList = cfList.Where(w => w.IsDefault == false); //非默认模块记录

            var intersectedList = from d in cfDefaultList join f in cfNoDefaultList on d.OrderNum equals f.OrderNum where d.IsDefault!= f.IsDefault select d;

            var newIntersectedList = intersectedList.Distinct().ToArray(); //排序号相同,既存在默认记录也存在非默认记录的数据 

                if (newIntersectedList != null && newIntersectedList.Length > 0)
                {
                    for (int i = 0; i < newIntersectedList.Length; i++)
                    {
                        if (newList.Contains(newIntersectedList[i]))
                        {
                            newList.Remove(newIntersectedList[i]);
                        }
                    }
                }
           newList = newList.OrderBy(x => x.OrderNum).ToList();

 以上的newList就代码截图中的数据。

出口缓存Output caching

优化API接口

有一个API接口平常卡顿,並且特不安宁,快的时候2~3秒,慢的时候10秒去了。

接口须要:依照社区ID获取减价券记录。

分析:

  • 担当给API接口提供数据的种类中,缺乏好些个索引,存在重重慢查询视图。
  • 原来的LINQ达成模式是在内部存款和储蓄器中分页,响应速度太慢。
  • 并发央浼的动静下,财富占用。

优化思路:

  数据缓存Data caching

1、使用缓存

同一个社区的人在同期所观察的打折券记录应当是一样的,何况大家相应允许脏读,我们在12306地点买火车票的时候,日常也拜谒到展现有票,可是下单又未有了,大概是选拔了缓存,那么我们这里实在同样的能够应用缓存来减轻并发难题。

在WebAPI上边加缓存,那么又分为客商端缓存和服务器缓存。而大家驾驭,在ASP.NET
WebForm和ASP.NET
MVC中都是有页面输出缓存的,而在WebAPI中默许未有,从NuGet上边下载WebApi.OutputCache.V2,然后再API接口上增加 

[CacheOutput(ClientTimeSpan = 5)]//, ServerTimeSpan = 5

自己这里无法直接采取服务器输出缓存,那是因为不可能捕获缓存变量参数。因为我们API接口的伸手参数是string
appParam,字符串类型的,它是叁个json对象进过base陆13个人编码,然后再进过url编码生成的字符串。

大家只好深入分析后,获取社区ID,然后依据社区ID来安装缓存,把社区ID+
pageIndex就作为缓存的Key,思虑到需求缓存的数据量相当的小,这里自个儿直接使用.NET自带的缓存,引进命名空间:System.Web.Caching;

      private static System.Web.Caching.Cache ObjCache = HttpRuntime.Cache;
        /// <summary>
        /// 设置当前指定Key的Cache值,并限定过期时间 
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="TimeOuts">超时时间(秒)</param>
        public static void SetCacheSeconds(string Key, object Obj, double TimeOuts)
        {
            ObjCache.Insert(Key, Obj, null, System.DateTime.Now.AddSeconds(TimeOuts), TimeSpan.Zero);
        }
        /// <summary>
        /// 获取当前指定Key的Cache值
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <returns>缓存的值</returns>
        public static object GetCache(string Key)
        {
            return ObjCache[Key];
        }

缓存操作类Cache完整代码如下:

亚洲必赢手机入口 2亚洲必赢手机入口 3

/*==================================
 * Author:
 * CreateTime:2014-7-15 17:26:29
 * Description:Cache操作类
 ===================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Runtime.CompilerServices;
using System.Web;
using System.Security.Policy;

namespace SSY.Util
{
    /// <summary>
    /// 缓存处理相关类
    /// </summary>
    public class Cache
    {
        private static System.Web.Caching.Cache ObjCache = HttpRuntime.Cache;
        private static short TimeOut = 720;

        #region 清除指定键值的缓存
        /// <summary>
        /// 清除指定键值的缓存
        /// </summary>
        /// <param name="Key">要清除的缓存的key值</param>
        public static void Clear(string Key)
        {
            if (ObjCache[Key] != null)
            {
                ObjCache.Remove(Key);
            }
        }
        #endregion

        #region 返回系统中缓存的个数
        /// <summary>
        /// 返回系统中缓存的个数
        /// </summary>
        /// <returns>缓存个数</returns>
        public static int Count()
        {
            return ObjCache.Count;
        }
        #endregion

        #region 获取当前指定Key的Cache值
        /// <summary>
        /// 获取当前指定Key的Cache值
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <returns>缓存的值</returns>
        public static object GetCache(string Key)
        {
            return ObjCache[Key];
        }
        #endregion

        #region 设置当前指定Key的Cache值
        /// <summary>
        /// 设置当前指定Key的Cache值 
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        public static void SetCache(string Key, object Obj)
        {
            ObjCache.Insert(Key, Obj);
        }
        #endregion

        #region 设置当前指定Key的Cache值,并限定过期时间
        /// <summary>
        /// 设置当前指定Key的Cache值,并限定过期时间 
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="TimeOuts">超时时间(分钟)</param>
        public static void SetCache(string Key, object Obj, int TimeOuts)
        {
            ObjCache.Insert(Key, Obj, null, System.DateTime.Now.AddMinutes((double)TimeOuts), TimeSpan.Zero);
        }
        /// <summary>
        /// 设置当前指定Key的Cache值,并限定过期时间 
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="TimeOuts">超时时间(秒)</param>
        public static void SetCacheSeconds(string Key, object Obj, double TimeOuts)
        {
            ObjCache.Insert(Key, Obj, null, System.DateTime.Now.AddSeconds(TimeOuts), TimeSpan.Zero);
        }
        #endregion

        #region 设置当前指定Key的Cache值,依赖文件过期
        /// <summary>
        /// 设置当前指定Key的Cache值,依赖文件过期 
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="Files">相对地址,例如"~/files.xml"</param>
        public static void SetCache(string Key, object Obj, string Files)
        {
            CacheDependency cacheDep = new CacheDependency(System.Web.HttpContext.Current.Server.MapPath(Files),System.DateTime.Now);
            SetCache(Key, Obj, TimeOut, cacheDep, CacheItemPriority.High);
        }
        #endregion

        #region 设置当前指定Key的Cache值
        /// <summary>
        /// 设置当前指定Key的Cache值
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="Priority">撤销缓存的优先值,此参数的值取自枚举变量“CacheItemPriority”,优先级低的数据项将先被删除。此参数主要用在缓存退出对象时.</param>
        public static void SetCache(string Key, object Obj, CacheItemPriority Priority)
        {
            SetCache(Key, Obj, TimeOut, null, Priority);
        }
        #endregion

        #region 设置当前指定Key的Cache值
        /// <summary>
        /// 设置当前指定Key的Cache值
        /// </summary>
        /// <param name="Key">缓存Key</param>
        /// <param name="Obj">缓存的值</param>
        /// <param name="TimeOuts">一个TimeSpan,表示缓存参数将在多长时间以后被删除</param>
        /// <param name="CacheDep">缓存的依赖项,需要一个CacheDependency,可初始化一个</param>
        /// <param name="Priority">撤销缓存的优先值,此参数的值取自枚举变量“CacheItemPriority”,优先级低的数据项将先被删除。此参数主要用在缓存退出对象时</param>
        public static void SetCache(string Key, object Obj, int TimeOuts, CacheDependency CacheDep, CacheItemPriority Priority)
        {
            ObjCache.Insert(Key, Obj, CacheDep, System.DateTime.MaxValue, TimeSpan.FromHours((double)TimeOuts), Priority, null);
        }
        #endregion
    }
}

View Code

修改API接口代码:

           #region added by zouqj 2017-3-7
           var result = Util.Cache.GetCache(CommunityID+ pageIndex) as Result<List<GetAvailableCouponsModel>>;
           if (result==null) //不存在则写入缓存
           {
               //组装参数
               Dictionary<string, string> inParams = new Dictionary<string, string>();
               inParams.Add("UserId", userId);
               inParams.Add("PageIndex", pageIndex);
               inParams.Add("PageSize", pageSize);
               inParams.Add("CommunityID", CommunityID+ pageIndex);
               ...

               RequestParam RequestParam = GetRequestParam(methodName, inParams, AuthenticationId);
               var jsonContent = JsonConvert.SerializeObject(RequestParam);
               result = DoPost<List<GetAvailableCouponsModel>>(jsonContent, PostUrl);

               Util.Cache.SetCacheSeconds(CommunityID, result, 10); //写入缓存
           }
           return result;

  1. 出口缓存(Output Caching)

2、改为存款和储蓄进程达成

因为这几个接口的业务逻辑比较复杂,在此之前的Linq代码写了好长一大串,获取的记录数非常多,并且依然在内存中进行分页达成,所以自身将本来的LINQ实现代码修改为分页存款和储蓄进度完毕。

积存进程代码如下:

亚洲必赢手机入口 4亚洲必赢手机入口 5

------------------------------------------创建领券中心存储过程 created by zouqj-2017-3-1-----------------------------------
IF EXISTS(Select Name From Sysobjects Where Name='usp_GetAvailableCoupons' And Xtype='P')
DROP PROCEDURE usp_GetAvailableCoupons
GO
CREATE PROC usp_GetAvailableCouponsl
(
@PageIndex int, --页码
@PageSize int, --每页容纳的记录数
@Sort NVARCHAR(50), --排序字段及规则,不用加order by
@hostName nvarchar(100),--服务器地址
@CommunityID UNIQUEIDENTIFIER, --社区
@IsGetCount BIT --是否得到记录总数,1为得到记录总数,0为不得到记录总数,返回记录集
)
AS
-------------------------------定义变量-----------------------
declare @strSql NVARCHAR(max);
DECLARE  @dt datetime2(7) --查询时间
SET @dt=GETDATE();
set nocount on;
----------------------------------------SQL开始--------------------------------------------无分类
IF @IsGetCount=1
BEGIN

SET @strSql=N'SELECT COUNT(*) FROM (SELECT DISTINCT t.CampaignID from
(SELECT 
c.ID AS CampaignID
 FROM MK_Campaign c WITH ( NOLOCK ) INNER JOIN MK_CouponConfig f WITH ( NOLOCK ) ON c.ID=f.CampaignID
           INNER JOIN MK_Coupon p WITH ( NOLOCK ) ON f.CouponID=p.ID
           WHERE f.CouponGetType=2 AND f.ReceiveStartTime <=@dt AND f.ReceiveEndTime>= @dt
           AND c.State=4 --执行中
           AND p.WholeNetwork=1 --全网优惠
UNION ALL
SELECT
    a.[ID] AS CampaignID
    FROM  [dbo].[MK_Campaign] AS a WITH ( NOLOCK )
        INNER JOIN [dbo].[MK_CouponConfig] AS b  WITH ( NOLOCK ) ON a.[ID] = b.[CampaignID]
        AND (b.[ReceiveStartTime] <= @dt) AND (b.[ReceiveEndTime] >= @dt) AND (2 = b.[CouponGetType]) AND (4 = a.[State]) 
        INNER JOIN [dbo].[MK_Coupon] AS c WITH ( NOLOCK ) ON b.[CouponID] = c.[ID]
        INNER JOIN [dbo].[MK_CouponRestriction] AS d  WITH ( NOLOCK ) ON c.[ID] = d.[CompainID]
        LEFT OUTER JOIN [dbo].[MK_CouponRestrictCategory] AS e WITH ( NOLOCK ) ON d.[ID] = e.[CouponRestrictionID]
        LEFT OUTER JOIN [dbo].[MK_CouponRestrictionOrg] AS f WITH ( NOLOCK ) ON d.[ID] = f.[CouponRestrictionID]
        INNER JOIN [dbo].[ViewOrganizationCommunityForInterface] AS v ON f.[OrgID] = v.[ID]    
    where v.CommunityID=@CommunityID  and 1 = d.[Type]
UNION ALL
SELECT 
   a.ID AS CampaignID
   FROM MK_Campaign a  WITH ( NOLOCK ) 
             INNER JOIN MK_CouponConfig b WITH ( NOLOCK ) ON a.ID=b.CampaignID AND (b.[ReceiveStartTime] <= @dt) AND (b.[ReceiveEndTime] >=@dt) 
             INNER JOIN [dbo].[MK_Coupon] AS c WITH ( NOLOCK ) ON b.[CouponID] = c.[ID] and (2 = b.[CouponGetType]) AND (4 = a.[State]) 
             INNER JOIN [dbo].[MK_CouponRestriction] AS d WITH ( NOLOCK ) ON c.[ID] = d.[CompainID]  AND (2 = d.[Type]) 
             LEFT OUTER JOIN MK_CouponRestrictionProduct AS e WITH ( NOLOCK ) ON d.[ID] = e.[CouponRestrictionID] 
             LEFT OUTER JOIN SL_Product AS f WITH ( NOLOCK ) ON (e.ProductID = f.ID)
             INNER JOIN ViewOrganizationCommunityForInterface v ON v.ID=f.PublisherID
   where v.CommunityID=@CommunityID
   ) t
 ) AS tt'
----------------------------------------------------------------------------------
END
ELSE
BEGIN
SET @strSql=N'SELECT DISTINCT t.* from(
SELECT 
          c.ID AS CampaignID,
          c.Name AS CampaignName,
          f.ValidityStartTime AS CampaignStartTime,
          f.ValidityEndTime AS CampaignEndTime,
          p.Name AS CouponsName,
          p.Price AS CouponsAmount,
          (CASE WHEN p.IsLimited =1 THEN 1 ELSE 2 END) AS IsLimited,
          p.FullAmount AS MinAmount,
          f.ValidityEndTime AS CouponsEndTime,
          f.ValidityStartTime AS CouponsStartTime,
          (CASE WHEN f.IsRepeateGet =1 THEN 1 ELSE 2 END) AS IsCanRepeatedReceive,
          f.ReceiveAddress AS ReceiveAddress,
          f.ReceiveEndTime AS ReceiveEndTime,
          f.ReceiveStartTime AS ReceiveStartTime,
          f.ReceiveMode AS ReceiveMethod,
          f.ProvideNum AS ReceiveNum,
          p.CreateTime AS CreateTime,
          p.Price AS Price,
          f.RemainCouponNum AS RemainCouponNum,
          f.ID AS CouponConfigId,
          p.WholeNetwork AS CouponsType,
          (CASE WHEN f.IconUrl IS NULL THEN N'''' WHEN f.IconUrl=N'''' THEN N'''' ELSE @hostName+f.IconUrl END) AS IconUrl 
FROM MK_Campaign c WITH ( NOLOCK ) 
                 INNER JOIN MK_CouponConfig f WITH ( NOLOCK ) ON c.ID=f.CampaignID
                 INNER JOIN MK_Coupon p WITH ( NOLOCK ) ON f.CouponID=p.ID
          WHERE f.CouponGetType=2 AND f.ReceiveStartTime <= @dt AND f.ReceiveEndTime>= @dt AND c.State=4 AND p.WholeNetwork=1 --全网优惠
--
UNION ALL
          SELECT a.[ID] AS CampaignID,
          a.[Name] AS CampaignName, 
          b.[ValidityStartTime] AS CampaignStartTime,
          b.[ValidityEndTime] AS CampaignEndTime, 
          c.[Name] AS CouponsName, 
          c.[Price] AS CouponsAmount, 
          CASE WHEN (c.[IsLimited] = 1) THEN 1 ELSE 2 END AS IsLimited, 
          c.[FullAmount] AS MinAmount, 
          b.[ValidityEndTime] AS CouponsEndTime, 
          b.[ValidityStartTime] AS CouponsStartTime, 
          CASE WHEN (b.[IsRepeateGet] = 1) THEN 1 ELSE 2 END AS IsCanRepeatedReceive, 
          b.[ReceiveAddress] AS [ReceiveAddress], 
          b.[ReceiveEndTime] AS [ReceiveEndTime], 
          b.[ReceiveStartTime] AS [ReceiveStartTime], 
          b.[ReceiveMode] AS ReceiveMethod, 
          b.[ProvideNum] AS ReceiveNum, 
          c.[CreateTime] AS CreateTime, 
          c.[Price] AS Price, 
          b.[RemainCouponNum] AS RemainCouponNum, 
          b.[ID] AS CouponConfigId, 
          e.[Type] AS CouponsType, 
          CASE WHEN (b.[IconUrl] = N'''' OR b.[IconUrl] IS NULL) THEN N'''' ELSE @hostName+b.[IconUrl] END AS IconUrl
                    FROM  [dbo].[MK_Campaign] AS a WITH ( NOLOCK )
                        INNER JOIN [dbo].[MK_CouponConfig] AS b  WITH ( NOLOCK ) ON a.[ID] = b.[CampaignID] AND (b.[ReceiveStartTime] <= @dt) AND (b.[ReceiveEndTime] >= @dt) AND (2 = b.[CouponGetType]) AND (4 = a.[State]) 
                        INNER JOIN [dbo].[MK_Coupon] AS c WITH ( NOLOCK ) ON b.[CouponID] = c.[ID]
                        INNER JOIN [dbo].[MK_CouponRestriction] AS d  WITH ( NOLOCK ) ON c.[ID] = d.[CompainID]
                        LEFT OUTER JOIN [dbo].[MK_CouponRestrictCategory] AS e WITH ( NOLOCK ) ON d.[ID] = e.[CouponRestrictionID]
                        LEFT OUTER JOIN [dbo].[MK_CouponRestrictionOrg] AS f WITH ( NOLOCK ) ON d.[ID] = f.[CouponRestrictionID]
                        INNER JOIN [dbo].[ViewOrganizationCommunityForInterface] AS v ON f.[OrgID] = v.[ID]    
                    where v.CommunityID=@CommunityID  and 1 = d.[Type]
UNION ALL
SELECT 
       a.ID AS CampaignID,
       a.Name AS CampaignName,
       b.ValidityStartTime AS CampaignStartTime,
       b.ValidityEndTime AS CampaignEndTime,
       c.Name AS CouponsName,
       c.Price AS CouponsAmount,
       (CASE WHEN c.IsLimited=1 then 1 else 2 END) AS IsLimited,
       c.FullAmount AS MinAmount,
       b.ValidityEndTime AS CouponsEndTime,
       b.ValidityStartTime AS CouponsStartTime,
       (case when b.IsRepeateGet=1 then 1 else 2 END) AS IsCanRepeatedReceive,
       b.ReceiveAddress AS ReceiveAddress,
       b.ReceiveEndTime AS ReceiveEndTime,
       b.ReceiveStartTime AS ReceiveStartTime,
       b.ReceiveMode AS ReceiveMethod,
       b.ProvideNum AS ReceiveNum,
       c.CreateTime AS CreateTime,
       c.Price AS Price,
       b.RemainCouponNum AS RemainCouponNum,
       b.ID AS CouponConfigId,
       d.[TYPE] AS CouponsType,
       (CASE WHEN b.IconUrl IS NULL THEN N'''' WHEN b.IconUrl=N'''' THEN N'''' ELSE @hostName+b.IconUrl END) AS IconUrl
   FROM MK_Campaign a  WITH ( NOLOCK ) 
                    INNER JOIN MK_CouponConfig b WITH ( NOLOCK ) ON a.ID=b.CampaignID AND (b.[ReceiveStartTime] <= @dt) AND (b.[ReceiveEndTime] >= @dt) 
                    INNER JOIN [dbo].[MK_Coupon] AS c WITH ( NOLOCK ) ON b.[CouponID] = c.[ID] and (2 = b.[CouponGetType]) AND (4 = a.[State]) 
                    INNER JOIN [dbo].[MK_CouponRestriction] AS d WITH ( NOLOCK ) ON c.[ID] = d.[CompainID]  AND (2 = d.[Type]) 
                    LEFT OUTER JOIN MK_CouponRestrictionProduct AS e WITH ( NOLOCK ) ON d.[ID] = e.[CouponRestrictionID] 
                    LEFT OUTER JOIN SL_Product AS f WITH ( NOLOCK ) ON (e.ProductID = f.ID)
                    INNER JOIN ViewOrganizationCommunityForInterface v ON v.ID=f.PublisherID
                    where v.CommunityID=@CommunityID
   ) t
ORDER BY t.Price--@Sort
offset (@PageIndex-1)*@PageSize ROWS  FETCH NEXT @PageIndex*@PageSize ROWS ONLY'
end
--执行SQL
exec sp_executesql @strSql,N'@PageIndex int,@PageSize int,@Sort nvarchar(50),@hostName nvarchar(100),@CommunityID UNIQUEIDENTIFIER,@IsGetCount bit,@dt datetime2(7)',@PageIndex =@PageIndex,@PageSize =@PageSize,@Sort=@Sort,@hostName=@hostName,@CommunityID=@CommunityID,@IsGetCount=@IsGetCount,@dt=@dt
set nocount off;

View Code

此间供给注意的是,存款和储蓄推行是,先关闭计数,set nocount on;,然后再展开set
nocount off;,这样能够升官品质。还会有正是利用WITH ( NOLOCK
)允许脏读,提高查询效用。

此处蒙受贰个很好看妙的主题素材,小编使用exec
sp_executesql
@strSql,N’….’的措施来举办是未有毛病的,而只要自己使用拼接sql的不二等秘书诀,会报错,因为sql字符串被截断了,只截取到了陆仟个字符长度,即使笔者把字符串变量长度设置为nvarchar(max)也没用。

分页格局选拔Sqlserver二〇一一以上版本才支撑的便捷格局:offset … FETCH NEXT
…ROWS ONLY

原来Linq的实行时间测量试验:

亚洲必赢手机入口 6BLW.png)亚洲必赢手机入口 7

自己修改为存储进度之后的实行时间测量检验:

亚洲必赢手机入口 8

品质差异十二分明显。

  使用输出缓存,你能够缓存最后输出的HTML页面,当一样的页面重新恳请的时候,ASP.NET不会再实行页面包车型大巴生命周期和连锁代码而是直接使用缓存的页面,语法如下:

  <%@
OutputCache Duration=”60” VaryByParam=”None”  %>

  Duration
属性设置页面将被缓存60妙。任何的客商诉求都会被缓存,在缓冲的60秒内一律的央求都会一向运用缓存的页面。当缓存过期后ASP.NET会再也施行页面代码並且为下壹个60秒创设二个新的HTML缓存。

<%@ Page Language=”C#” MastERPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”OutputCachingTest.aspx.cs” Inherits=”OutputCachingTest” Title=”Page” %> 
<%@ OutputCache Duration=”20″ VaryByParam=”None” %> 
<asp:Content ID=”Content1″ ContentPlaceHolderID=”ContentPlaceHolder1″ runat=”Server”>  
   <div class=”title”>Output
Cache</div> 
   Date: <asp:Label ID=”lblDate” runat=”server” Text=”” /> 
   Time: <asp:Label ID=”lblTime” runat=”server” Text=”” />        
</asp:Content>

 

protected void Page_Load(object sender, EventArgs e) 

  lblDate.Text = DateTime.Now.ToShortDateString(); 
  lblTime.Text = DateTime.Now.ToLongTimeString(); 
}

   在那些例子中页面将被缓存20秒。

  由此查询字符串缓存(Cache by Query String )

  在骨子里运用中页面往往会基于一些参数动态的改观页面包车型客车内容。假如你的页面是因此询问字符串来获取音讯的,你能够依靠查询字符串很轻便的缓存页面包车型大巴不等拷贝。VarByParam=”None”内定ASP.NET只存款和储蓄缓存页面包车型大巴五个拷贝。VarByParam=”*”
钦赐ASP.NET依据不一样的查询字符串存储分裂的缓存页面。

<%@ OutputCache
Duration=”60″ VaryByParam=”*” %> 
<div align=”right”> 
   <a href=”OutputCachingTest2.aspx”>No
Query String</a> |  
   <a href=”OutputCachingTest2.aspx?id=1″>ID
1</a> |  
   <a href=”OutputCachingTest2.aspx?id=2″>ID
2</a> |  
   <a href=”OutputCachingTest2.aspx?id=3″>ID
3</a> | 
   <a href=”OutputCachingTest2.aspx?id=3&langid=1″>ID
3</a> 
</div>

 

  下边的事例中,在询问字符串中传了区别的ID.ASP.NET为每一个ID都存款和储蓄了独自的缓存页面。这种方法会有局部主题材料正是当查问字符串范围很广的时候。

  那年大家得以在VarByParam
属性中钦赐首要的查询字符串变量的名字,如下:

  %@OutputCacheDuration=”60″VaryByParam=”id;langid”%

 

  那样,ASP.NET能够依据id” or “langid”来缓存不相同的缓存版本。

  自定义缓存(Custom Caching)

  你也能够创建自定义的次第来缓存页面。ASP.net提供了一种很便捷的不二等秘书籍来创造自定义缓存,使用VarByCustom属性钦定自定义缓存类型的名字。

  你还要创立为缓存生成自定义字符串的点子,如下:

  public override stringGetVaryByCustomString(HttpContext
context, stringcustom) 
  { 
  if(custom == “browser”) 
  { 
  returncontext.Request.Browser.Browser + 
  context.Request.Browser.MajorVersion; 
  } 
  else 
  { 
  return base.GetVaryByCustomString(context, custom); 
  } 
  }

 

  那些格局必得写在global.asax文件中。ASP.NET使用该方法再次回到的字符串来促成缓存,假如那个法子在差别的乞求中回到一样的字符串,ASP.NET就能够利用缓存的页面,不然就能够扭转新的缓存版本。

  下边的例证中GetVaryByCustomString()方法依据浏览器的名字创办缓存字符串,ASP.NET会依据不一致的浏览器恳求创立不相同版本的缓存。

  控件缓存(Control Cache )

  上边的缓存技术能够令你很轻便的缓存整个页面,要是要缓存钦点控件的内容,能够透过点名VaryByControl
属性来实现。

  %@OutputCacheDuration=”20″VaryByControl=”MyControl_1″%

 

  下面代码ASP.NET将会缓存MyControl_1控件20分钟。假若要依据部分属性值来缓存控件只要求将OutPutCache指令出席*.ascx页面。

<%@Control Language=”C#”AutoEventWireup=”true”CodeFile=”MyControl.ascx.cs” 
Inherits=”Controls_MyControl”%> 
<%@OutputCacheDuration=”20″VaryByControl=”EmployeeID”%>  

  VaryByControl=”EmployeeID”告诉ASP.NET根据控件中宣称的EmployeeID属性来创立差异版本的缓存。

  在 .ascx.cs 文件到场EmplyeeID属性为ASP.NET 缓存使用。

  在页面中加进控件何况安装 EmployeeID.

    private int_employeeID; 
  public intEmployeeID 
  { 
  get{ return_employeeID; } 
  set{ _employeeID = value;

  } 
  protected voidPage_Load(objectsender, EventArgs e) 
  { 
  lblDate.Text = DateTime.Now.ToShortDateString(); 
  lblTime.Text = DateTime.Now.ToLongTimeString(); 
  lblEmployeeID.Text = EmployeeID.ToString(); 
  }

 

     缓存配置文件(Cache Profile )

  Web.config能够配备缓存相关的装置,

  <system.web> 
  <caching> 
    <outputCacheSettings> 
      <outputCacheProfiles> 
        <addname=”ProductItemCacheProfile” duration=”60″/> 
      </outputCacheProfiles> 
    </outputCacheSettings> 
  </caching> 
</system.web>

 

   你能够因此设置 CacheProfile=”ProfileName” 属性 来使用方面包车型大巴安排:

  %@OutputCacheCacheProfile=”ProductItemCacheProfile”VaryByParam=”None”%

 

  2. 多少缓存(Data Caching)

  ASP.net还提供了另一种灵活的缓存类型:数据缓存。你能够将一些消耗费时间间的条约到场到三个对象缓存会集中,以键值的章程存款和储蓄。

  Cache[“Name”] = data;

  我们能够经过应用Cache.Insert()方法来设置缓存的晚点,优先级,依赖项等。

  date1 = DateTime.Now;Cache.Insert(“Date1”, date1, null,
DateTime.Now.AddSeconds(20), TimeSpan.Zero);

  ASP.NET允许你设置一个相对过期时间或滑动过期日子,但不能够并且采取。

  缓存信赖项Cache dependency

  缓存信任项使缓存重视于其余财富,当正视项改成时,缓存条款项将活动从缓存中移除。缓存信任项能够是应用程序的
Cache 中的文件、目录或与其余对象的键。假若文件或目录更换,缓存就能晚点。

    date2 = DateTime.Now; 
  string[] cacheKeys = { “Date1”}; 
  CacheDependency cacheDepn = newCacheDependency(null,
cacheKeys); 
  Cache.Insert(“Date2”, date2,
cacheDepn);

 

  上边的事例“Date2”缓存对象信任“Date1”缓存条约,当 “Date1”
对象过期后“Date2” 将会活动过期。CacheDependency(null,
cacheKeys)中的第八个参数为空是出于大家只监视缓存键的改变意况。

  回调函数和缓存优先级(Callback Method and Cache Priority)

  ASP.NET允许大家写一个回调函数,当缓存条约从缓存中移除的时候接触。还足以安装缓存条目款项标事先级。

  protected void Page_Load(object sender, EventArgs e) 
  { 
  DateTime? date1 = (DateTime?)Cache[“Date1”]; 
  if (!date1.HasValue) // date1 ==
null 
  { 
  date1 = DateTime.Now; 
  Cache.Insert(“Date1”,
date1, null, DateTime.Now.AddSeconds(20),
TimeSpan.Zero, 
  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack)); 
  } 
  DateTime? date2 = (DateTime?)Cache[“Date2”]; 
  if (!date2.HasValue) // date2 ==
null 
  { 
  date2 = DateTime.Now; 
  Cache.Insert(“Date2”,
date2, null, DateTime.Now.AddSeconds(40),
TimeSpan.Zero, 
  CacheItemPriority.Default, new CacheItemRemovedCallback(CachedItemRemoveCallBack)); 
  } 
  // Set values in labels 
  lblDate.Text = date1.Value.ToShortDateString(); 
  lblTime.Text = date1.Value.ToLongTimeString(); 
  lblDate1.Text = date2.Value.ToShortDateString(); 
  lblTime1.Text = date2.Value.ToLongTimeString(); 
  } 
  private void CachedItemRemoveCallBack(string key, object value, CacheItemRemovedReason reason) 
  { 
  if (key == “Date1” || key == “Date2”) 
  { 
  Cache.Remove(“Date1”); 
  Cache.Remove(“Date2”); 
  } 
  }

 

  例子中开创了“Date1” 和 “Date2”缓存。“Date1”
在20秒后过期“Date2”为40秒。可是由于大家报了名了移除的回调函数,当“Date1”
或 “Date2”个中三个过期都会举办CachedItemRemoveCallBack
方法,在那么些主意中移除了八个缓存条款,ASP.NET还提供了管理缓存条约更新时的回调函数CacheItemUpdateCallback

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图