ASP.NET Web API是一项伟大的技术。编写Web API十分容易,以至于许多开发者都不愿花时间去想办法架构应用程序以获得更好的性能。
这篇文章中,我个人总结出了用于改善 ASP.NET Web API 性能的八项技术。
1) 使用最快速的 JSON serializer
JSON serialization 能极大的影响ASP.NET Web API的整体性能。在一年半的时间里,我已经从某个项目中的JSON.NET serializer转到了ServiceStack.Text 。
现在的我的Web API 响应已经提升了约20%。强烈建议尝试这个serializer。以下是几个热门serializers最新的性能对比:
2) 手动从DataReader创建JSON串
我将这种方法用在我的产品项目上,获得了很多性能方面的益处。
不必从 DataReader读取值后填充对象,然后转而又从那些对象读取值,最后使用某个JSON Serializer生成JSON。我是说你可以直接手动从DataReader 创建JSON串,从而避免创建不必要的对象。 先是用 StringBuilder生成JSON,最后你返回StringContent 作为你webAPI中的反馈内容。
1
2
3
4
5
|
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content =
new
StringContent(jsonResult, Encoding.UTF8,
"application/json"
);
return
response;
|
更加详细的内容请看 Rick Strahl的blog
3) 尽使用其他格式 (protocol buffer, message pack)
如果你能够在项目中使用其他格式如 Protocol Buffers 或MessagePack 而不是 JSON 的话那就赶紧换了吧。这样你可以获取极大的性能提升,这不仅是因为Protocol Buffers更快,还因为格式比JSON小,所以响应速度也就更迅速。
4) 压缩
在你的ASP.NET Web API使用 GZIP 或 Deflate压缩。压缩是文件包瘦身和加速的一种行之有效的方法。
该功能必须要有,具体内容可查阅我先前的博文 ASP.NET Web API GZip compression ActionFilter with 8 lines of code.
5) 缓存机制
要是觉得有道理的话,在你的Web API methods试试输出缓存(output caching )。
如果你想要实现手动缓存,例如将用户口令缓存到内存上,可以参考我的博文Simple way to implement caching in ASP.NET Web API.
6) 尽可能使用典型ADO.NET
手动编码ADO.NET仍是从数据库获取数据的最快捷方式。如果你真的很看重Web API的性能的话就不要使用ORMs。
可以参考下列这几个热门ORMs的最新性能对比:
Dapper和hand-written fetch code 如同预期那样,速度都非常快。所有ORMs都比前面三个慢。
LLBLGen 速度也很快,但它先得获取结果集然后再重新从内存实现对象。
7) 实现异步
用异步Web API服务能够增加Web API 所能处理的并发HTTP请求的数量。
要实现很简单。该操作用async关键词标记,返回类型变为Task。
1
2
3
4
5
6
7
8
9
10
|
[HttpGet]
public
async Task OperationAsync()
{
await Task.Delay(2000);
}
|
8) 返回多个结果集并合并结果
减少至数据库和Web API的往返数量。应该尽可能使用多个结果集功能。这意味着你可以从DataReader提取多个结果集,就像下面这个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
// read the first resultset
var
reader = command.ExecuteReader();
// read the data from that resultset
while
(reader.Read())
{
suppliers.Add(PopulateSupplierFromIDataReader( reader ));
}
// read the next resultset
reader.NextResult();
// read the data from that second resultset
while
(reader.Read())
{
products.Add(PopulateProductFromIDataReader( reader ));
}
|
在一次 Web API响应中返回尽可能多的对象。 试着把所有对象结合成一个汇总的:
1
2
3
4
5
6
7
8
9
10
11
|
public
class
AggregateResult
{
public
long MaxId { get; set; }
public
List<folder> Folders{ get; set; }
public
List<user> Users{ get; set; }
}</user></folder>
|
通过这种方法就能减少你的Web API的HTTP请求数量。