连接错误Google Cloud Function到Cloud SQL

时间:2018-12-28 17:12:03

标签: google-cloud-platform google-cloud-functions google-cloud-sql

使用将云函数连接到Cloud SQL的示例代码,我成功创建了一个输出稍有不同的新函数。暂时运行良好。现在,对代码没有任何更改,我得到了OperationalError:(2003,“无法连接到'localhost'上的MySQL服务器([Errno 111]连接被拒绝)”)。这是完整的错误:

sql-test-function-1
szzv41dltb8k
Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 570, in connect sock.connect(self.unix_socket) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 297, in run_http_function result = _function_handler.invoke_user_function(flask.request) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 199, in invoke_user_function return call_user_function(request_or_event) File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 192, in call_user_function return self._user_function(request_or_event) File "/user_code/main.py", line 50, in mysql_demo mysql_conn = pymysql.connect(**mysql_config) File "/env/local/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 327, in __init__ self.connect() File "/env/local/lib/python3.7/site-packages/pymysql/connections.py", line 629, in connect raise exc pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")

我在这里和Google GitHub支持上都看到过许多有类似问题的人的例子,并尝试了所有解决方案(启用Cloud SQL Admin API,在this Stackoverflow question中实现答案等),但是我不断收到相同的错误。我尝试重新启动SQL实例以及在Chrome Incognito窗口中使用相同的代码创建新函数,以避免缓存问题:相同的错误。

这是我有关云功能的代码:

from os import getenv

import pymysql
from pymysql.err import OperationalError

# TODO(developer): specify SQL connection details
CONNECTION_NAME = getenv(
  'INSTANCE_CONNECTION_NAME',
  'la-cloud-functions:us-central1:cf-sql-1')
DB_USER = getenv('MYSQL_USER', 'root')
DB_PASSWORD = getenv('MYSQL_PASSWORD', 'root')
DB_NAME = getenv('MYSQL_DATABASE', 'gallery')

mysql_config = {
  'user': DB_USER,
  'password': DB_PASSWORD,
  'db': DB_NAME,
  'charset': 'utf8mb4',
  'cursorclass': pymysql.cursors.DictCursor,
  'autocommit': True
}

# Create SQL connection globally to enable reuse
# PyMySQL does not include support for connection pooling
mysql_conn = None


def __get_cursor():
    """
    Helper function to get a cursor
      PyMySQL does NOT automatically reconnect,
      so we must reconnect explicitly using ping()
    """
    try:
        return mysql_conn.cursor()
    except OperationalError:
        mysql_conn.ping(reconnect=True)
        return mysql_conn.cursor()


def mysql_demo(request):
    global mysql_conn

    # Initialize connections lazily, in case SQL access isn't needed for this
    # GCF instance. Doing so minimizes the number of active SQL connections,
    # which helps keep your GCF instances under SQL connection limits.
    if not mysql_conn:
        try:
            mysql_conn = pymysql.connect(**mysql_config)
        except OperationalError:
            # If production settings fail, use local development ones
            mysql_config['unix_socket'] = f'/cloudsql/{CONNECTION_NAME}'
            mysql_conn = pymysql.connect(**mysql_config)

    # Remember to close SQL resources declared while running this function.
    # Keep any declared in global scope (e.g. mysql_conn) for later reuse.
    with __get_cursor() as cursor:
        cursor.execute('SELECT * from albums')
        row = cursor.fetchone()
        while row is not None:
          print(row)
          row = cursor.fetchone()

如果有人有其他建议,我会很高兴。

TIA-乔

1 个答案:

答案 0 :(得分:0)

我通过在另一个项目中重新创建函数来解决了这个问题。我不确定Cloud SQL实例为何断开连接并无法连接,但是一旦我重新建立连接,就能够成功地重新应用该函数中的代码。从Cloud Function到Cloud SQL的连接仍处于正式测试阶段,因此可能只是暂时的故障。