简体   繁体   English

如何使用部署在 firebase 中的函数连接到我的谷歌云 mysql 数据库?

[英]how can I connect to my google cloud mysql database using a function deployed in firebase?

I deployed this function in firebase to connect to my google cloud mysql database:我在 firebase 中部署了这个函数来连接到我的谷歌云 mysql 数据库:

const functions = require('firebase-functions');

const mysql = require('mysql');

const connectionName = process.env.INSTANCE_CONNECTION_NAME || 'xxx';
const dbUser = process.env.SQL_USER || 'xxx';
const dbPassword = process.env.SQL_PASSWORD || 'xxx';
const dbName = process.env.SQL_NAME || 'xxx';

const mysqlConfig = {
  connectionLimit: 1,
  user: dbUser,
  password: dbPassword,
  database: dbName,
  socketPath: `/cloudsql/${connectionName}`,
};

if (process.env.NODE_ENV === 'production') {
  mysqlConfig.socketPath = `/cloudsql/${connectionName}`;
}

let mysqlPool;

exports.populateDatabase = functions.https.onRequest ((req, res) => {
  if (!mysqlPool) {
    mysqlPool = mysql.createPool(mysqlConfig);
  }

  mysqlPool.query('SELECT * from exercise', (err, results) => {
    if (err) {
      console.error(err);
      res.status(500).send(err);
    } else {
      res.send(JSON.stringify(results));
    }
  });

});

Then clicking on the generated link in firebase the result is this one:然后点击 firebase 中生成的链接,结果是这样的:

{"errno":"ECONNREFUSED","code":"ECONNREFUSED","syscall":"connect","address":"/cloudsql/xxx","fatal":true} {"errno":"ECONNREFUSED","code":"ECONNREFUSED","syscall":"connect","address":"/cloudsql/xxx","fatal":true}

how can I solve the problem?我该如何解决问题?

The complete instructions to connect to Cloud SQL from Cloud Function is in the documentation , and are too long to simply list here.从 Cloud Function 连接到 Cloud SQL 的完整说明在文档中,因为太长而无法在此处简单列出。 I suggest reading over them very carefully.我建议非常仔细地阅读它们。

One thing important thing to note is this statement from that page:需要注意的一件重要事情是该页面的以下声明:

Note: These instructions require your Cloud SQL instance to have a public IP address.注意:这些说明要求您的 Cloud SQL 实例具有公共 IP 地址。 If you want to use a private IP address, see Configuring Serverless VPC Access and connect directly using the private IP.如果要使用私有 IP 地址,请参阅配置无服务器 VPC 访问并使用私有 IP 直接连接。

So, if you're trying to access with a private IP address, you will have to set up a VPC to connect to it.因此,如果您尝试使用私有 IP 地址进行访问,则必须设置一个 VPC 以连接到它。

Assuming you have a SQL database with an external ip address then you can connect using this code.假设您有一个带有外部 IP 地址的 SQL 数据库,那么您可以使用此代码进行连接。 The most important step is to deploy your cloud function with the following Environment Variable: CLOUD_SQL_CONNECTION_NAME = your-project:us-central1:your-instance .最重要的步骤是使用以下环境变量部署您的云功能: CLOUD_SQL_CONNECTION_NAME = your-project:us-central1:your-instance This will start the cloud sql proxy for you.这将为您启动云 sql 代理。


/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */



exports.connect= (req, res) => {


  var mysql = require('mysql');



  var pool = mysql.createPool({
    socketPath: `/cloudsql/your-project:us-central1:your-instance`,
    user            : 'test',
    password        : 'root',
    database        : 'data',
    connectionLimit : 10,               // this is the max number of connections before your pool starts waiting for a release
    multipleStatements : true           // I like this because it helps prevent nested sql statements, it can be buggy though, so be careful
});




  pool.getConnection(function (err, conn) {
    if (err)
        return res.send(400);

    // if you got a connection...
    conn.query('SHOW DATABASES', function(err, rows) {
        if(err) {
            conn.release();
            return res.send(400, 'Couldnt get a connection');
        }

        // for simplicity, just send the rows
        res.status(200).send(rows);

        // CLOSE THE CONNECTION
        conn.release();
    })

    });




};

TEST THE FUNCTION:测试功能:

[{"Database":"information_schema"},{"Database":"data"},{"Database":"mydatabase"},{"Database":"mysql"},{"Database":"performance_schema"},{"Database":"sys"}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从已部署的Firebase应用程序中获取云功能 - How can I GET from a Cloud Function from a Deployed Firebase App 如何使用phonegap连接到sdcard中现有的数据库? - How can I connect with database existing in my sdcard using phonegap? 如何使用Google Cloud功能查询Firebase实时数据库 - How to query Firebase Realtime database using Google Cloud functions 如何将值从Google Cloud Function(Firebase)传递到前端? - How can i pass values from google cloud function (firebase) to front end? 为什么我的 Firebase Cloud Function 不能使用“allAuthenticatedUsers”? - Why can't I use `allAuthenticatedUsers` for my Firebase Cloud Function? 如何使用 Cloud Functions 计划对我的 Firebase Firestore 数据库中的集合进行批量更新? - How do I schedule a batch update to a collection in my Firebase Firestore database using Cloud Functions? 如何使用云函数从我的 Firebase 实时数据库中 database.ref 正在侦听的节点内部获取数据? - How can I fetch data from inside a node which the database.ref is listening to in my Firebase real-time database using cloud functions? 我如何使用node.js函数检查我的VM实例在google-cloud中使用了多少CPU和内存 - How can I check how many CPUs and memory my vm instance uses in google-cloud using node.js function 如何在谷歌云中连接到我的 SSH VPS? - How do I connect to my SSH VPS in google cloud? 如何在云端功能中查询Firebase数据库? - How do I query a firebase database inside a cloud function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM