我要求在10秒内处理多达5000个。问题是红K中似乎存在瓶颈。并发客户端请求越多,读取第一个请求正文的延迟就越大。简约的测试控制台应用程序如下:
public interface IMyHandler
{
Func<HttpContext, string> Handler { get; set; }
}
public class MyHandler : IMyHandler
{
public Func<HttpContext, string> Handler { get; set; }
}
public class Startup : IStartup
{
IMyHandler MyHandler;
public Startup(IMyHandler h)
{
MyHandler = h;
}
public void Configure(IApplicationBuilder app)
{
var this_ = this;
app.Run(context =>
{
MyHandler.Handler(context);
var response = String.Format("Hello, Universe! It is {0}", DateTime.Now);
return context.Response.WriteAsync(response);
});
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services
return services.BuildServiceProvider();
}
}
class Program
{
static void Main(string[] args)
{
EventWaitHandle success = new AutoResetEvent(false);
var sentRequests = 0;
var serverTask = Task.Run(() =>
{
MyHandler h1 = new MyHandler();
h1.Handler = (context) =>
{
using (BufferedStream buffer = new BufferedStream(context.Request.Body))
{
using (var reader = new StreamReader(buffer))
{
var body = reader.ReadToEnd();
var _sent = sentRequests;
//success.Set();
}
}
return "OK";
};
var host = new WebHostBuilder()
.UseKestrel((context, options) =>
{
//options.ApplicationSchedulingMode = SchedulingMode.Inline;
options.ListenAnyIP(21122, listenOptions =>
{
});
})
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureServices(services =>
{
services.Add(Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton(typeof(IMyHandler), h1));
})
//.UseIISIntegration()
.UseStartup<Startup>()
//.UseApplicationInsights()
.Build();
host.Run();
});
Enumerable.Range(0, 100).ForEach((n) => {
var clientTask = Task.Run(async () =>
{
var handler = new HttpClientHandler();
HttpClient client = new HttpClient(handler);
sentRequests++;
var p1 = await client.PostAsync("http://localhost:21122", new StringContent("{test:1}", Encoding.UTF8, "application/json"));
});
});
Assert.IsTrue(success.WaitOne(new TimeSpan(0, 0, 50)));
}
}
对于给出的100个请求,我在读取第一正文时已经有大约12秒的延迟。要看到这一点,只需在线设置断点
var _sent = sentRequests;
sendRequests也等于100,这意味着(实际上有点推测,但似乎是合理的)此时所有请求都已发送。在我看来,这似乎是由单线程完成的,而当它接受请求时,它并不会开始读取它们。
有什么办法可以克服这个问题吗?