我正试图弄清楚为什么我的webservice这么慢,并想办法让它更快地响应。当前不涉及自定义处理(即apicontroller操作返回非常简单的对象)的平均响应时间约为75ms。
设置
机器:
-
32GB RAM、固态硬盘、4 x 2.7GHz CPU、8个逻辑处理器、x64 Windows 10
软件
-
1个在iisexpress上运行.NET 4.0的ASP.NET MVC网站(system.web.mvc v5.2.7.0)
-
1个在iisexpress上运行.NET 4.0的ASP.NET Web API网站(system.net.http v4.2.0.0)
-
1 RabbitMQ消息总线
ASP.NET Web API代码(API控制器操作)
[Route("Send")]
[HttpPost]
[AllowAnonymous)
public PrimitiveTypeWrapper<long> Send(WebsiteNotificationMessageDTO notification)
{
_messageBus.Publish<IWebsiteNotificationCreated>(new { Notification = notification });
return new PrimitiveTypeWrapper<long>(1);
}
这个方法的主体需要2毫秒。stackify告诉我authenticationfilterresult.executeasync方法有很多开销,但是由于它是一个asp.net的东西,我认为它不能被优化太多。
ASP.NET MVC代码(MVC控制器操作)
restclient实现如下所示。httpclientfactory返回一个新的httpclient实例,其中包含必需的头和basepath。
public async Task<long> Send(WebsiteNotificationMessageDTO notification)
{
var result = await _httpClientFactory.Default.PostAndReturnAsync<WebsiteNotificationMessageDTO, PrimitiveTypeWrapper<long>>("/api/WebsiteNotification/Send", notification);
if (result.Succeeded)
return result.Data.Value;
return 0;
}
在后端rest服务上尽快执行100个请求:
[HttpPost]
public async Task SendHundredNotificationsToMqtt()
{
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100; i++)
{
await _notificationsRestClient.Send(new WebsiteNotificationMessageDTO()
{
Severity = WebsiteNotificationSeverity.Informational,
Message = "Test notification " + i,
Title = "Test notification " + i,
UserId = 1
});
}
sw.Stop();
Debug.WriteLine("100 messages sent, took {0} ms", sw.ElapsedMilliseconds);
}
平均需要7.5秒。
我试过的东西
-
检查了rest服务和mvc网站上的可用线程数:
int workers;
int completions;
System.Threading.ThreadPool.GetMaxThreads(out workers, out completions);
两种情况都有:
Workers: 8191
Completions: 1000
-
删除了所有rabbitmq消息总线连接以确保不是罪魁祸首。我还从rest方法中删除了messagebus publish方法
_messageBus.Publish<IWebsiteNotificationCreated>(new { Notification = notification });
所以它所做的就是在包装对象中返回1。
-
后端rest使用带有承载令牌身份验证的身份框架,为了消除其中的大部分,我还尝试将rest服务上的控制器操作标记为allowanonymous。
-
以发布模式运行项目:无更改
-
运行示例100请求两次以排除服务初始化开销:无更改
在所有这些尝试之后,问题仍然存在,每个请求仍需要大约+75毫秒。这是最低的吗?
下面是应用了上述更改的后端stackify日志。
web服务仍然很慢,这是因为没有昂贵的硬件升级,它可以得到的速度一样快,还是有其他的东西,我可以调查,找出是什么使我的web服务这么慢?