【问题标题】:FATAL: too many connections for role: Heroku/django, only while using ASGI致命:角色连接过多:Heroku/django,仅在使用 ASGI 时
【发布时间】:2020-06-05 22:59:45
【问题描述】:

我知道还有其他类似的问题,但我相信我已经解决了所有问题,但没有一个能够解决我的问题。 当我使用 WSGI 服务器时,一切正常。只有当我使用 ASGI 服务器时才会发生这种情况,但是我必须使用 ASGI 服务器,因为没有它我的项目功能会受到限制。我正在使用 postgres 数据库。

另外,我相信在 localhost 上运行项目时没有问题,因为我检查了到我的数据库(在我的机器上进行开发)的连接数,我只看到了 1 个。那 1 个连接也不是来自django 项目到我的数据库,但这是我自己用来显式访问数据库的连接。我不知道为什么我的项目与数据库之间甚至没有一个连接。

Procfile

    web: daphne aretheycoming.asgi:application --port $PORT --bind 0.0.0.0 -v2
    aretheycomingworker: python manage.py runworker --settings=aretheycoming.settings -v2
asgi.py

    import os
    import django
    from channels.routing import get_default_application

    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aretheycoming.settings")
    django.setup()
    application = get_default_application()
settings.py

    import django_heroku

    import os

    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = hidden

    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True

    ALLOWED_HOSTS = []


    # Application definition

    INSTALLED_APPS = [
        'channels',
        .
        .
        .
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    ROOT_URLCONF = 'aretheycoming.urls'

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

    WSGI_APPLICATION = 'aretheycoming.wsgi.application'
    ASGI_APPLICATION = 'aretheycoming.routing.application'

    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [('127.0.0.1', 6379)],
                "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')]
            },
        },
    }


    # Database
    # https://docs.djangoproject.com/en/2.2/ref/settings/#databases

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': hidden,
            'USER': hidden,
            'PASSWORD': hidden,
            'HOST': '127.0.0.1',
            'PORT': '5432',
        }
    }


    # Password validation
    # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]


    # Internationalization
    # https://docs.djangoproject.com/en/2.2/topics/i18n/

    LANGUAGE_CODE = 'en-us'

    TIME_ZONE = 'UTC'

    USE_I18N = True

    USE_L10N = True

    USE_TZ = True


    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/2.2/howto/static-files/

    STATIC_ROOT = ''

    STATIC_URL = '/static/'

    STATICFILES_DIRS = [
        os.path.join(BASE_DIR, 'static'),
    ]

    # Activate Django-Heroku.
    django_heroku.settings(locals())

我尝试使用 django.db.close_all_connections() 但它不起作用,并且该项目在 wsgi 服务器上运行良好,所以我认为这不是问题。 我对这些东西没有很好的理解,所以如果你能多做一点解释,我将不胜感激。

我在 Heroku 上设置了环境变量 ASGI_THREADS = 1。

【问题讨论】:

    标签: django heroku database-connection asgi


    【解决方案1】:

    https://devcenter.heroku.com/articles/postgres-logs-errors#fatal-too-many-connections-for-role

    同时建立多个连接也实现了异步。这就是它使用超过 1 个连接的原因。

    该用户遇到了同样的问题并提供了解决方案:Django/Heroku: FATAL: too many connections for role

    【讨论】:

    • 我在 heroku 上设置了环境变量。它甚至在 ASGI_THREADS = 1 上也不起作用
    【解决方案2】:

    我找到了一个似乎运行良好的解决方案。 解决方案是pgbouncer。通过执行以下命令将 pgbouncer 安装到 heroku:

    heroku buildpacks:add https://github.com/heroku/heroku-buildpack-pgbouncer
    
    heroku buildpacks:add heroku/python
    

    之后,如果您部署到 Heroku,您可能会在 Heroku 日志中看到以下错误-

    heroku server does not support SSL, but SSL was required
    

    LtKvasirhere 给出了一个非常简单的解决方案。

    我的代码中到处都有 db.connections.close_all(),但我认为现在真的没有必要了。

    【讨论】:

      猜你喜欢
      • 2019-01-01
      • 2014-09-23
      • 1970-01-01
      • 2021-09-14
      • 2012-08-25
      • 2023-03-11
      • 2018-07-16
      • 1970-01-01
      • 2017-04-16
      相关资源
      最近更新 更多