热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

WebAPI性能优化之压缩解压

有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持。在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显

有时候为了提升WebAPI的性能,减少响应时间,我们会使用压缩和解压,而现在大多数客户端浏览器都提供了内置的解压支持。在WebAPI请求的资源越大时,使用压缩对性能提升的效果越明显,而当请求的资源很小时则不需要使用压缩和解压,因为压缩和解压同样也是需要耗费一定的时间的。

看见老外写了一篇ASP.NET Web API GZip compression ActionFilter with 8 lines of code

说实话被这标题吸引了,8行代码实现GZip压缩过滤器,我就照着他的去实践了一番,发现居然中文出现乱码。

按照他的实现方式:

1、下载DotNetZipLib库

2、解压后添加Ionic.Zlib.dll的dll引用

技术分享图片

3、新建DeflateCompression特性和GZipCompression特性,分别代表Deflate压缩和GZip压缩,这两种压缩方式的实现代码很相似

不同的地方就是

actContext.Response.Content.Headers.Add("Content-encoding", "gzip");

actContext.Response.Content.Headers.Add("Content-encoding", "deflate");

  var compressor = new DeflateStream(
                    output, CompressionMode.Compress,
                    CompressionLevel.BestSpeed)
 var compressor = new GZipStream(
                    output, CompressionMode.Compress,
                    CompressionLevel.BestSpeed)
技术分享图片
using System.Net.Http;
using System.Web.Http.Filters;

namespace WebAPI.Filter
{
    public class GZipCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actContext)
        {
            var cOntent= actContext.Response.Content;
            var bytes = cOntent== null ? null : content.ReadAsByteArrayAsync().Result;
            var zlibbedCOntent= bytes == null ? new byte[0] :
            CompressionHelper.GZipByte(bytes);
            actContext.Response.COntent= new ByteArrayContent(zlibbedContent);
            actContext.Response.Content.Headers.Remove("Content-Type");
            actContext.Response.Content.Headers.Add("Content-encoding", "gzip");
            actContext.Response.Content.Headers.Add("Content-Type", "application/json");
            base.OnActionExecuted(actContext);
        }
    }
}
using System.Net.Http;
using System.Web.Http.Filters;

namespace WebAPI.Filter
{
    public class DeflateCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuted(HttpActionExecutedContext actContext)
        {
            var cOntent= actContext.Response.Content;
            var bytes = cOntent== null ? null : content.ReadAsByteArrayAsync().Result;
            var zlibbedCOntent= bytes == null ? new byte[0] :
            CompressionHelper.DeflateByte(bytes);
            actContext.Response.COntent= new ByteArrayContent(zlibbedContent);
            actContext.Response.Content.Headers.Remove("Content-Type");
            actContext.Response.Content.Headers.Add("Content-encoding", "deflate");
            actContext.Response.Content.Headers.Add("Content-Type", "application/json");
            base.OnActionExecuted(actContext);
        }
    }
技术分享图片

4、添加一个压缩帮助类CompressionHelper

技术分享图片
using System.IO;
using Ionic.Zlib;

namespace WebAPI.Filter
{
    public class CompressionHelper
    {
        public static byte[] DeflateByte(byte[] str)
        {
            if (str == null)
            {
                return null;
            }

            using (var output = new MemoryStream())
            {
                using (
                    var compressor = new DeflateStream(
                    output, CompressionMode.Compress,
                    CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }
        public static byte[] GZipByte(byte[] str)
        {
            if (str == null)
            {
                return null;
            }
            using (var output = new MemoryStream())
            {
                using (
                    var compressor = new GZipStream(
                    output, CompressionMode.Compress,
                    CompressionLevel.BestSpeed))
                {
                    compressor.Write(str, 0, str.Length);
                }

                return output.ToArray();
            }
        }
    }
}
技术分享图片

5、控制器调用,这里我写的测试代码:

技术分享图片
    public class TestController : ApiController
    {
        StringBuilder sb = new StringBuilder();
        
        [GZipCompression]
        public string Get(int id)
        {
            for (int i = 0; i <1000;i++ )
            {
                sb.Append("这里是中国的领土" + i);
            }
            return sb.ToString() + DateTime.Now.ToLocalTime() + "," + id;
        }
    }
技术分享图片

先看下不使用压缩,注释//[GZipCompression] 标记,文件大小是26.4kb,请求时间是1.27s

技术分享图片

使用[GZipCompression]标记,添加压缩后,文件大小是2.4kb,响应时间是1.21,Respouse Body明显小了很多,但是响应时间少得并不明显,因为在本地环境下载太快了,而压缩解压却要消耗一定的时间,界面加载的时间主要消耗在onload上了。有个问题:中文显示乱码了。

技术分享图片

 使用.net自带的压缩,在System.IO.Compression中提供了对应的类库——GZipStream与DeflateStream。控制器调用代码不变,新建一个CompressContentAttribute.cs类,代码如下:

技术分享图片
技术分享图片
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPI.Filter
{
    // 
    /// 自动识别客户端是否支持压缩,如果支持则返回压缩后的数据
    /// Attribute that can be added to controller methods to force content
    /// to be GZip encoded if the client supports it
    /// 
    public class CompressContentAttribute : ActionFilterAttribute
    {
        /// 
        /// Override to compress the content that is generated by
        /// an action method.
        /// 
        /// 
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            GZipEncodePage();
        }

        /// 
        /// Determines if GZip is supported
        /// 
        /// 
        public static bool IsGZipSupported()
        {
            string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
            if (!string.IsNullOrEmpty(AcceptEncoding) &&
                    (AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate")))
                return true;
            return false;
        }

        /// 
        /// Sets up the current page or handler to use GZip through a Response.Filter
        /// IMPORTANT:
        /// You have to call this method before any output is generated!
        /// 
        public static void GZipEncodePage()
        {
            HttpResponse RespOnse= HttpContext.Current.Response;

            if (IsGZipSupported())
            {
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];

                if (AcceptEncoding.Contains("deflate"))
                {
                    Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
                                               System.IO.Compression.CompressionMode.Compress);
                    #region II6不支持此方法,(实际上此值默认为null 也不需要移除)
                    //Response.Headers.Remove("Content-Encoding");
                    #endregion
                    Response.AppendHeader("Content-Encoding", "deflate");
                }
                else
                {
                    Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
                                                 System.IO.Compression.CompressionMode.Compress);
                    #region II6不支持此方法,(实际上此值默认为null 也不需要移除)
                    //Response.Headers.Remove("Content-Encoding");
                    #endregion
                    Response.AppendHeader("Content-Encoding", "gzip");
                }
            }

            // Allow proxy servers to cache encoded and unencoded versions separately
            Response.AppendHeader("Vary", "Content-Encoding");
        }
    }

    /// 
    /// 强制Defalte压缩
    /// Content-encoding:gzip,Content-Type:application/json
    /// DEFLATE是一个无专利的压缩算法,它可以实现无损数据压缩,有众多开源的实现算法。
    /// 
    public class DeflateCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            HttpResponse RespOnse= HttpContext.Current.Response;
            Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
                                              System.IO.Compression.CompressionMode.Compress);
            #region II6不支持此方法,(实际上此值默认为null 也不需要移除)
            //Response.Headers.Remove("Content-Encoding");
            #endregion
            Response.AppendHeader("Content-Encoding", "deflate");
        }
    }

    /// 
    /// 强制GZip压缩,application/json
    /// Content-encoding:gzip,Content-Type:application/json
    /// GZIP是使用DEFLATE进行压缩数据的另一个压缩库
    /// 
    public class GZipCompressionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            HttpResponse RespOnse= HttpContext.Current.Response;
            Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
                                              System.IO.Compression.CompressionMode.Compress);
            #region II6不支持此方法,(实际上此值默认为null 也不需要移除)
            //Response.Headers.Remove("Content-Encoding");
            #endregion
            Response.AppendHeader("Content-Encoding", "gzip");
        }
    }
}
技术分享图片

运行查看结果,压缩能力比DotNetZipLib略差,但是不再出现乱码了。

技术分享图片

把控制器代码中的标记改为   [DeflateCompression],使用Deflate压缩再来看下效果:

 技术分享图片

Deflate压缩后,Content-Length值为2538,而GZip压缩Content-Length值为2556,可见Deflate压缩效果更好。

这里,WebAPI的压缩我都是通过Action过滤器的方式来实现,当然你也可以写在WebAPI中的全局配置中,考虑到有些API接口并不需要使用到压缩,所以就通过Action过滤器的方式来实现了。

dudu的这篇文章HttpClient与APS.NET Web API:请求内容的压缩与解压在客户端压缩、在服务端解压。

WebAPI性能优化之压缩解压


推荐阅读
  • 导出功能protectedvoidbtnExport(objectsender,EventArgse){用来打开下载窗口stringfileName中 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • 《数据结构》学习笔记3——串匹配算法性能评估
    本文主要讨论串匹配算法的性能评估,包括模式匹配、字符种类数量、算法复杂度等内容。通过借助C++中的头文件和库,可以实现对串的匹配操作。其中蛮力算法的复杂度为O(m*n),通过随机取出长度为m的子串作为模式P,在文本T中进行匹配,统计平均复杂度。对于成功和失败的匹配分别进行测试,分析其平均复杂度。详情请参考相关学习资源。 ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • Redis底层数据结构之压缩列表的介绍及实现原理
    本文介绍了Redis底层数据结构之压缩列表的概念、实现原理以及使用场景。压缩列表是Redis为了节约内存而开发的一种顺序数据结构,由特殊编码的连续内存块组成。文章详细解释了压缩列表的构成和各个属性的含义,以及如何通过指针来计算表尾节点的地址。压缩列表适用于列表键和哈希键中只包含少量小整数值和短字符串的情况。通过使用压缩列表,可以有效减少内存占用,提升Redis的性能。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 拥抱Android Design Support Library新变化(导航视图、悬浮ActionBar)
    转载请注明明桑AndroidAndroid5.0Loollipop作为Android最重要的版本之一,为我们带来了全新的界面风格和设计语言。看起来很受欢迎࿰ ... [详细]
  • 本文介绍了作者在开发过程中遇到的问题,即播放框架内容安全策略设置不起作用的错误。作者通过使用编译时依赖注入的方式解决了这个问题,并分享了解决方案。文章详细描述了问题的出现情况、错误输出内容以及解决方案的具体步骤。如果你也遇到了类似的问题,本文可能对你有一定的参考价值。 ... [详细]
  • 本文介绍了一个在线急等问题解决方法,即如何统计数据库中某个字段下的所有数据,并将结果显示在文本框里。作者提到了自己是一个菜鸟,希望能够得到帮助。作者使用的是ACCESS数据库,并且给出了一个例子,希望得到的结果是560。作者还提到自己已经尝试了使用"select sum(字段2) from 表名"的语句,得到的结果是650,但不知道如何得到560。希望能够得到解决方案。 ... [详细]
  • 怎么在PHP项目中实现一个HTTP断点续传功能发布时间:2021-01-1916:26:06来源:亿速云阅读:96作者:Le ... [详细]
  • 浏览器中的异常检测算法及其在深度学习中的应用
    本文介绍了在浏览器中进行异常检测的算法,包括统计学方法和机器学习方法,并探讨了异常检测在深度学习中的应用。异常检测在金融领域的信用卡欺诈、企业安全领域的非法入侵、IT运维中的设备维护时间点预测等方面具有广泛的应用。通过使用TensorFlow.js进行异常检测,可以实现对单变量和多变量异常的检测。统计学方法通过估计数据的分布概率来计算数据点的异常概率,而机器学习方法则通过训练数据来建立异常检测模型。 ... [详细]
  • 第四章高阶函数(参数传递、高阶函数、lambda表达式)(python进阶)的讲解和应用
    本文主要讲解了第四章高阶函数(参数传递、高阶函数、lambda表达式)的相关知识,包括函数参数传递机制和赋值机制、引用传递的概念和应用、默认参数的定义和使用等内容。同时介绍了高阶函数和lambda表达式的概念,并给出了一些实例代码进行演示。对于想要进一步提升python编程能力的读者来说,本文将是一个不错的学习资料。 ... [详细]
  • Windows7 64位系统安装PLSQL Developer的步骤和注意事项
    本文介绍了在Windows7 64位系统上安装PLSQL Developer的步骤和注意事项。首先下载并安装PLSQL Developer,注意不要安装在默认目录下。然后下载Windows 32位的oracle instant client,并解压到指定路径。最后,按照自己的喜好对解压后的文件进行命名和压缩。 ... [详细]
author-avatar
手机用户2602890793
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有