Asp.net Web Api开发(第二篇)性能:使用Jil提升Json序列化性能

本文介绍通过替换默认的Newtonsoft.Json序列化库为Jil,显著提升了ASP.NET WebAPI服务端性能。Jil不仅速度快,而且易于集成。文中详细记录了替换步骤,并提供了具体的实现代码。

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


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

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

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

第二部:编写一个JilFormatter:

using Jil;
using System;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RRPService.WebApi.Comm
{
    public class JilFormatter: MediaTypeFormatter
    {
        private readonly Options mJilOptions;

        /// <summary>
        /// Jil Json序列化器
        /// </summary>
        public JilFormatter()
        {
            mJilOptions = new Options(
                dateFormat: DateTimeFormat.MillisecondsSinceUnixEpoch,
                excludeNulls:true,
                includeInherited: true,
                serializationNameFormat: SerializationNameFormat.CamelCase);
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
            SupportedEncodings.Add(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true));
            SupportedEncodings.Add(new UnicodeEncoding(bigEndian: false, byteOrderMark: true, throwOnInvalidBytes: true));
        }
        public override bool CanReadType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            return true;
        }
        public override bool CanWriteType(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            return true;
        }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.FromResult(this.DeserializeFromStream(type, readStream));
        }
        private object DeserializeFromStream(Type type, Stream readStream)
        {
            try
            {
                using (var reader = new StreamReader(readStream))
                {
                    MethodInfo method = typeof(JSON).GetMethod("Deserialize", new Type[] { typeof(TextReader), typeof(Options) });
                    MethodInfo generic = method.MakeGenericMethod(type);
                    return generic.Invoke(this, new object[] { reader, mJilOptions });
                }
            }
            catch
            {
                return null;
            }
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, System.Net.Http.HttpContent content, TransportContext transportContext)
        {
            var streamWriter = new StreamWriter(writeStream);
            JSON.Serialize(value, streamWriter, mJilOptions);
            streamWriter.Flush();
            return Task.FromResult(writeStream);
        }
    }
}
替换默认Json序列化库:

using RRPService.WebApi.Comm;
using System.Web.Http;
using System.Web.Mvc;

namespace RRPService.WebApi.App
{
    /// <summary>
    /// web api 服务
    /// </summary>
    public class WebApiApplication : System.Web.HttpApplication
    {
        /// <summary>
        /// 服务启动
        /// </summary>
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            HttpConfiguration fConfig = GlobalConfiguration.Configuration;
            fConfig.Formatters.Remove(fConfig.Formatters.JsonFormatter);
            fConfig.Formatters.Insert(0, new JilFormatter());
        }
    }
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值