【问题标题】:Have EntityFramework respect mysql max_user_connections让 EntityFramework 尊重 mysql max_user_connections
【发布时间】:2016-04-18 18:43:11
【问题描述】:

如果 max_user_connections 连接已经打开,有没有办法告诉 Entity Framework 等待?

我想我可以捕捉到异常并重试或保留一个计数器,但这充其量只是感觉很老套。

我的 Azure 日志充满了以下消息:

System.Data.Entity.Core.EntityException: The underlying provider failed on Open. 
MySql.Data.MySqlClient.MySqlException: 
Authentication to host 'xxx' for user 'yyy' using method 'mysql_native_password' failed with message: 
User 'yyy' has exceeded the 'max_user_connections' resource (current value: 4)

我尝试将Max Pool Size=4 添加到连接字符串,但没有帮助。

<add name="DbContext" connectionString="Database=db;Data Source=xxx;User Id=yyy;Password=zzz;CharSet=utf8;Persist Security Info=True;Convert Zero Datetime=True;Max Pool Size=4" providerName="MySql.Data.MySqlClient" />

【问题讨论】:

  • max_user_connections 是一个数据库参数,所以 EF 在登录之前无法知道它。我相信你能做的最好的就是捕获异常并处理它。
  • 我知道每个环境的max_user_connections。有什么办法可以告诉 EF 不要打开更多连接?
  • 您可以将其作为参数管理并在上下文构造函数中进行处理,但在应用程序的所有实例之间同步此值会非常麻烦。我相信最好的方法是抓住那个例外。

标签: c# mysql entity-framework azure asp.net-web-api2


【解决方案1】:

按照 Vito 的建议:捕获异常并让前端决定做什么:

在后端,我使用了PostSharp,这是针对.NET 的Aspect-Oriented programming 的实现。它允许我用一个属性来装饰我所有的存储库来处理这个特定的异常。

在前端我可能会做一些事情,比如等待 400 毫秒,然后在放弃之前再试 1-3 次。

在包管理器控制台中:
Install-Package PostSharp

你还需要安装一个PostSharp plugin for Visual Studio

[Serializable]
public class MaxMysqlConnectionExceptionHandlerAspect : OnExceptionAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        if (args.Exception.InnerException != null && args.Exception.InnerException.Message.Contains("Too many connections"))
        {
            args.FlowBehavior = FlowBehavior.ThrowException;
            args.Exception = new Exception("MAX_CONNECTIONS");
        }
    }

    public override Type GetExceptionType(MethodBase method)
    {
        return typeof(EntityException);
    }
}

然后装饰类或方法:

[MaxMysqlConnectionExceptionHandlerAspect]
public class FancyPantsService {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-01
    • 2015-09-26
    • 2011-07-13
    • 1970-01-01
    相关资源
    最近更新 更多