1

ASP.NET MVC3 应用程序使用 npgsql 2.0.12.0 通过 mod_mono 获取 Mono 中的数据。有时会发生以下超时异常。如果发生异常,请求持续时间为 31 秒。

使用连接字符串中的 CommandTimeout 设置为 5 分钟

        NpgsqlConnectionStringBuilder csb = new NpgsqlConnectionStringBuilder()
        {
            CommandTimeout = 5*60,  // 5 min
            Host = Config.Server,
            Database = Config.DefaultDataBase,
            UserName = Config.ServerUser,
            Port = Config.Port,
            SslMode = SslMode.Prefer,
            SSL = true,
        };

如何强制 npgsql 使用超时 5 分钟而不是在 31 秒后抛出异常?在 postgresql.con 文件中 statement_timeout 没有设置,所以看起来这不是来自服务器。

使用 ExecuteReader 执行查询:

        using (IDbConnection conn = DataAccessBase.CreateConnection())
        using (IDbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = string.Format(command, paramNames);
            conn.Open();
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection | CommandBehavior.SingleResult))
            {
                if (reader.Read())
                {
                    string[] names = new string[reader.FieldCount];
                    for (int i = 0; i < names.Length; i++)
                    {
                        names[i] = reader.GetName(i);
                    }
                    Func<IDataRecord, MyDataContext, T> objInit = InitializerCache<T>.GetInitializer(names, ConvertValue != null);
                    do
                    { // walk the data 
                        yield return objInit(reader, this);
                    } while (reader.Read());
                }
                while (reader.NextResult()) { } // ensure any trailing errors caught 
            }
        }

请求开始后 31 秒后发生异常。

请求头:

Connection  Keep-alive
Accept  */*
Accept-Encoding gzip,deflate
From    googlebot(at)googlebot.com
User-Agent  Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)

例外:

Npgsql.NpgsqlException:
A timeout has occured. If you were establishing a connection, increase Timeout value in ConnectionString. If you were executing a command, increase the CommandTimeout value in ConnectionString or in your NpgsqlCommand object.
  at Npgsql.NpgsqlState.ProcessBackendResponsesEnum (Npgsql.NpgsqlConnector context) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlReadyState.QueryEnum (Npgsql.NpgsqlConnector context, Npgsql.NpgsqlCommand command) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlConnector.QueryEnum (Npgsql.NpgsqlCommand queryCommand) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlCommand.GetReader (CommandBehavior cb) [0x00000] in <filename unknown>:0 
  at Npgsql.NpgsqlCommand.ExecuteReader (CommandBehavior cb) [0x00000] in <filename unknown>:0 
4

1 回答 1

-3

抱歉,但我认为您的 CommandTime 不正确:

CommandTimeout = 5*60, // 5 min

它是 30 秒(300 毫秒)。

于 2013-09-25T10:27:59.163 回答