Asp.net Web Api开发 性能:使用Jil提升Json序列化性能

from:http://blog.csdn.net/sqqyq/article/details/51692342

看了几篇网上关于各种序列化工具的性能对比,在这里再粘贴下:


我们使用了ASP.NET WEB API来提供RESTfull风格的接口给APP调用,默认序列化库用的是:Newtonsoft.Json

为了进一步提高服务端的性能,有必要将序列化库进行替换。从上图可以看出,Jil是最快的Json序列化库了。为了验证其性能,我们也写了相关代码,将Jil和Newtonsoft.Json进行的比较。确实Jil的性能要优越不少。于是决定就用Jil来替换了。

第一步:引用Jil.dll,同目录下也要有Sigil.dll,Jil是基于Sigil开发的。

第二部:编写一个JilFormatter:

[csharp]  view plain  copy
  1. using Jil;  
  2. using System;  
  3. using System.IO;  
  4. using System.Net;  
  5. using System.Net.Http.Formatting;  
  6. using System.Net.Http.Headers;  
  7. using System.Reflection;  
  8. using System.Text;  
  9. using System.Threading.Tasks;  
  10.   
  11. namespace RRPService.WebApi.Comm  
  12. {  
  13.     public class JilFormatter: MediaTypeFormatter  
  14.     {  
  15.         private readonly Options mJilOptions;  
  16.   
  17.         /// <summary>  
  18.         /// Jil Json序列化器  
  19.         /// </summary>  
  20.         public JilFormatter()  
  21.         {  
  22.             mJilOptions = new Options(  
  23.                 dateFormat: DateTimeFormat.MillisecondsSinceUnixEpoch,  
  24.                 excludeNulls:true,  
  25.                 includeInherited: true,  
  26.                 serializationNameFormat: SerializationNameFormat.CamelCase);  
  27.             SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));  
  28.             SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));  
  29.             SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));  
  30.         }  
  31.         public override bool CanReadType(Type type)  
  32.         {  
  33.             if (type == null)  
  34.             {  
  35.                 throw new ArgumentNullException("type");  
  36.             }  
  37.             return true;  
  38.         }  
  39.         public override bool CanWriteType(Type type)  
  40.         {  
  41.             if (type == null)  
  42.             {  
  43.                 throw new ArgumentNullException("type");  
  44.             }  
  45.             return true;  
  46.         }  
  47.         public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)  
  48.         {  
  49.             return Task.FromResult(this.DeserializeFromStream(type, readStream));  
  50.         }  
  51.         private object DeserializeFromStream(Type type, Stream readStream)  
  52.         {  
  53.             try  
  54.             {  
  55.                 using (var reader = new StreamReader(readStream))  
  56.                 {  
  57.                     MethodInfo method = typeof(JSON).GetMethod("Deserialize"new Type[] { typeof(TextReader), typeof(Options) });  
  58.                     MethodInfo generic = method.MakeGenericMethod(type);  
  59.                     return generic.Invoke(thisnew object[] { reader, mJilOptions });  
  60.                 }  
  61.             }  
  62.             catch  
  63.             {  
  64.                 return null;  
  65.             }  
  66.         }  
  67.         public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)  
  68.         {  
  69.             var streamWriter = new StreamWriter(writeStream);  
  70.             JSON.Serialize(value, streamWriter, mJilOptions);  
  71.             streamWriter.Flush();  
  72.             return Task.FromResult(writeStream);  
  73.         }  
  74.     }  
  75. }  
替换默认Json序列化库:

[csharp]  view plain  copy
  1. using RRPService.WebApi.Comm;  
  2. using System.Web.Http;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace RRPService.WebApi.App  
  6. {  
  7.     /// <summary>  
  8.     /// web api 服务  
  9.     /// </summary>  
  10.     public class WebApiApplication : System.Web.HttpApplication  
  11.     {  
  12.         /// <summary>  
  13.         /// 服务启动  
  14.         /// </summary>  
  15.         protected void Application_Start()  
  16.         {  
  17.             GlobalConfiguration.Configure(WebApiConfig.Register);  
  18.             HttpConfiguration fConfig = GlobalConfiguration.Configuration;  
  19.             fConfig.Formatters.Remove(fConfig.Formatters.JsonFormatter);  
  20.             fConfig.Formatters.Insert(0, new JilFormatter());  
  21.         }  
  22.     }  
  23. }  

猜你喜欢

转载自blog.csdn.net/paolei/article/details/79613541