如何运行 Google Cloud SQL 只在我需要的时候使用?

How to run Google Cloud SQL only when I need it?

Google Cloud SQL 宣传说最小的机器类型每小时只需 0.0150 美元,而且我按小时收费,而不仅仅是我连接的小时数。这是因为我正在使用游泳池吗?我如何设置我的后端,以便它仅在需要时查询云数据库,这样我就不会在一天中的每个小时都被收费?

const mysql      = require('mysql');
const pool = mysql.createPool({
    host : process.env.SQL_IP,
    user     : 'root',
    password : process.env.SQL_PASS,
    database : 'mydb',
    ssl      : {
          [redacted]
    }
});

function query(queryStatement, cB){
  pool.getConnection(function(err, connection) {
    // Use the connection
    connection.query(queryStatement, function (error, results, fields) {
      // And done with the connection.
      connection.destroy();
      // Callback
      cB(error,results,fields);

    });
  });
}

这与其说是关于池,不如说是关于云的性质 SQL。与 App Engine 不同,云 SQL 实例 始终 可用。一个星期六的早上,当我离开这个项目一个星期时,我以艰难的方式学到了这一点。 :)

除非您明确停止服务,否则无法在不使用时将它们关闭。

无法安排 服务停止,至少在 GCP SDK 中是这样。您总是可以编写一个 cron 作业或类似的东西,它在例如当地时间 M-F 下午 6 点运行一点 gcloud sql instances patch [INSTANCE_NAME] --activation-policy NEVER 命令。我懒得这样做,所以我只是为自己设置了一个日历提醒,以便在我的工作日结束时关闭我的实例。

这是当前 SDK 文档的 MySQL 实例 start/stop/restart 页面: https://cloud.google.com/sql/docs/mysql/start-stop-restart-instance

另外请注意,正在进行'Feature Request' in the GCP Platform to start/stop the Cloud SQL (2nd Gen), according to the traffic as well. You can also visit the link并在那里提供您宝贵的suggestions/comments。

我从@ingernet 那里得到了灵感并创建了一个云函数,在需要时 starts/stops CloudSQL 实例。它可以通过计划作业触发,因此您可以定义实例何时启动或关闭。

详细信息在此处 Github Gist (inspiration taken from here)。 免责声明:我不是 python 开发人员,因此代码中可能存在问题,但最终它有效。


基本上您需要按照以下步骤操作:

  1. 创建一个pub/sub主题,用于触发云功能。
  2. Create the cloud function 并复制下面的代码。
    1. 确保在第 8 行设置正确的项目 ID。
    2. 将触发器设置为 Pub/Sub 并选择在步骤 1 中创建的主题。
  3. Create a cloud scheduler job定期触发云功能。
    1. 选择触发云功能的频率。
    2. 将目标设置为 Pub/Sub 并定义在步骤 1 中创建的主题。
    3. 应将有效负载设置为 start [CloudSQL instance name]stop [CloudSQL instance name] 以启动或停止指定的实例(例如 start my_cloudsql_instance 将启动名称为 my_cloudsql_instance 的 CloudSQL 实例)

Main.py:

from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
import base64
from pprint import pprint

credentials = GoogleCredentials.get_application_default()
service = discovery.build('sqladmin', 'v1beta4', credentials=credentials, cache_discovery=False)
project = 'INSERT PROJECT_ID HERE'

def start_stop(event, context):
  print(event)
  pubsub_message = base64.b64decode(event['data']).decode('utf-8')
  print(pubsub_message)
  command, instance_name = pubsub_message.split(' ', 1)

  if command == 'start':
    start(instance_name)
  elif command == 'stop':
    stop(instance_name)
  else:
    print("unknown command " + command)

def start(instance_name):
  print("starting " + instance_name)
  patch(instance_name, "ALWAYS")

def stop(instance_name):
  print("stopping " + instance_name)
  patch(instance_name, "NEVER")

def patch(instance, activation_policy):
  request = service.instances().get(project=project, instance=instance)
  response = request.execute()

  dbinstancebody = {
    "settings": {
      "settingsVersion": response["settings"]["settingsVersion"],
      "activationPolicy": activation_policy
    }
  }

  request = service.instances().patch(
    project=project,
    instance=instance,
    body=dbinstancebody)
  response = request.execute()
  pprint(response)

Requirements.txt

google-api-python-client==1.10.0
google-auth-httplib2==0.0.4
google-auth==1.19.2
oauth2client==4.1.3