博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WebAPI性能优化之压缩解压
阅读量:6946 次
发布时间:2019-06-27

本文共 8860 字,大约阅读时间需要 29 分钟。

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

看见老外写了一篇

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

按照他的实现方式:

1、下载库

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"); } }}
View Code

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

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

 

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

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

dudu的这篇文章在客户端压缩、在服务端解压。

转载地址:http://jbenl.baihongyu.com/

你可能感兴趣的文章
java对象与字符串之间的序列化和反序列化
查看>>
人工智障 2 : 你看到的AI与智能无关
查看>>
Let's Encrypt 使用教程,免费的SSL证书,让你的网站拥抱 HTTPS
查看>>
.net 面试题系列四(附答案)
查看>>
sql server的并发性
查看>>
windows php启动浏览器
查看>>
CPP_类模板与模板类
查看>>
用CocoaPods做iOS程序的依赖管理
查看>>
gallery图片展示(图片间隔)
查看>>
[下一个话题]利用NodeJs+Html5+WebSocket快速构建即时在线简易PPT
查看>>
如何在Exchange Server 2007集线器传输服务器角色上使用防垃圾邮件功能
查看>>
Redis持久化相关问题
查看>>
maven-war-plugin参数说明
查看>>
Qt学习之路(18): Qt标准对话框之QInputDialog
查看>>
java中OutOfMemory种类和解决方法
查看>>
OpenNLP-Sentence Detector
查看>>
Cordova3.3在android平台下的配置方法
查看>>
ExtJs+SHH实现异步树节点搜索和查找
查看>>
go的变量作用域
查看>>
nginx 出现413 Request Entity Too Large问题的解决方法
查看>>