0

我创建了一个新的空 asp.net 核心项目并键入如下代码。但是 QPS 大约在 600 左右。(hello world test php 6000,asp.net core 10000,带有 PDO 的 php 在 1000 左右做同样的工作)

Ubuntu 20.04 ab -c 1000 -n 50000 http://localhost:4246/

 app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            var list = new List<Dictionary<string, string>>();
            MySqlConnection myConnnect;
            MySqlCommand sqlCmd;
            myConnnect = new MySqlConnection(constructorString);
            sqlCmd = new MySqlCommand();
            sqlCmd.Connection = myConnnect;
            sqlCmd.CommandText = "select * from location where parent_id=0";
            await myConnnect.OpenAsync();
            
            using (var reader = await sqlCmd.ExecuteReaderAsync(System.Data.CommandBehavior.CloseConnection))
            {
                while (await reader.ReadAsync())
                {
                    var data = new Dictionary<string, string>();
                    data["id"] = reader.GetInt32(0).ToString();
                    data["spell_first"] = reader.GetString(2);
                    data["spell_full"] = reader.GetString(3);
                    data["name"] = reader.GetString(4);
                    list.Add(data);
                }
            }


            await context.Response.WriteAsync("Hello World!");
        });
4

1 回答 1

0

由于您的重点是单个线程每秒的查询,而不是针对运行查询的大量线程进行优化,您可以尝试让阅读器以非异步方式读取。这将避免在阅读记录时为您的线程切换上下文。

此外,这可能是更大的问题,使用字典来保存记录的字段将涉及更多的内存管理,然后为它们使用专用类,所以我建议也进行更改。最终代码可能如下所示:

[注意我没有运行这段代码,因为我没有你的数据库;-)所以代码可能有语法错误]

public class Rec{
    public int Id;
    public string SpellFirst;
    public string SpellFull;
    public string Name;
}

app.UseEndpoints(endpoints =>
    {
        endpoints.MapGet("/", async context =>
        {
            var list = new List<Rec>();
            MySqlConnection myConnnect;
            MySqlCommand sqlCmd;
            myConnnect = new MySqlConnection(constructorString);
            sqlCmd = new MySqlCommand();
            sqlCmd.Connection = myConnnect;
            sqlCmd.CommandText = "select * from location where parent_id=0";
            await myConnnect.OpenAsync();
            
            using (var reader = await sqlCmd.ExecuteReaderAsync(System.Data.CommandBehavior.CloseConnection))
            {
                while (reader.Read())
                {
                    var rec = new Rec();
                    rec.Id = reader.GetInt32(0).ToString();
                    rec.SpellFirst = reader.GetString(2);
                    rec.SpellFull = reader.GetString(3);
                    rec.Name = reader.GetString(4);
                    list.Add(rec);
                }
            }


            await context.Response.WriteAsync("Hello World!");
        });

试一试,看看数字是多少。

于 2021-02-05T13:44:44.337 回答