【问题标题】:How to read data form cloud SQL in Google Cloud Function in Node JS如何在 Node JS 中的 Google Cloud Function 中从云 SQL 读取数据
【发布时间】:2022-02-08 00:56:22
【问题描述】:

我是谷歌云函数的新手,我在这里尝试从云 SQL 加载数据,因为我已经编写了一个代码,该代码具有数据库连接以及 SQL 查询字符串,但是当我尝试测试函数时它会抛出错误或对象或有时它说您没有返回任何数据。我尝试了很多方法来发送数据,但仍然对我不起作用。提前致谢。

代码sn-ps,

exports.welcome = async (req, res) => {
  const tag = req?.body?.fulfillmentInfo?.tag;
  let message = tag || req?.query?.message || req?.body?.message || 'Hello World!';

  const pool = mysql.createPool({
    connectionLimit: 1,
    host: '10.30.48.2',
    user: 'root',
    password: 'TEST@TEST',
    database: 'hospital_assist'
  });
  
  const jsonResponse = {
    fulfillment_response: {
      messages: [
        {
          text: {
            //fulfillment text response to be sent to the agent
            text: [`Welcome entry point ${message}`],
          },
        },
      ],
    },
  };

  let qResult = await pool.query('SELECT * FROM Patients;');
  // pool.query('SELECT * FROM Patints', (error, result) => {
  //   console.log(error);
  //   console.log(result);
  //   console.log('In loop');
  //   res.status(200).send(jsonResponse);  
  // });



  // await pool.query('select * from Patients;', (error, results) => {
  //       if (error) {
  //           console.log(error);
  //           res.status(200).send(jsonResponse);
  //       }
  //       qResult = results;
  //       // res.send(results);
  //   });

  console.log(qResult);
  console.log(`In loop ${qResult}`);
  res.status(200).send(JSON.stringify(qResult)); 

  // res.status(200).send(jsonResponse);
};

【问题讨论】:

  • 您是否向 Cloud Functions 添加了无服务器 VPC 连接器?您的 Cloud SQL 实例上是否有公共 IP?如果是这样,您的 SQL 引擎是什么(MySQL 或 postgreSQL)?
  • 我有公共和私有 IP。 SQL 引擎是 MySQL。

标签: node.js google-cloud-platform google-cloud-functions google-cloud-sql


【解决方案1】:

如果您尝试使用公共 IP 连接到您的实例,则需要指定 Unix 套接字路径,例如,

mysql.createPool({
    user: process.env.DB_USER, // e.g. 'my-db-user'
    password: process.env.DB_PASS, // e.g. 'my-db-password'
    database: process.env.DB_NAME, // e.g. 'my-database'
    // If connecting via unix domain socket, specify the path
    socketPath: "/cloudsql/my-project:us-central1:my-instance",
    // Specify additional properties here.
    ...config,
});

详情请见the docs

【讨论】:

    【解决方案2】:

    在你的情况下,你有几个解决方案,特别推荐2个:

    • 使用内部 IP(您当前的代码)。使用该模式,您可以删除公共 IP 并从 Internet 完全隐藏数据库。要允许 CLoud Functions 访问私有 IP,您必须将无服务器世界(服务器和网络由 Google Cloud 为您管理,因此您不在您的 VPC 中)与您的项目世界(尤其是您的数据库所在的 VPC已连接)。 serverless VPC connector 就是为此而做的。
    • 借助 Cloud Functions,您可以使用 built-in connector with Cloud SQL MySQL(仅在版本 8 中)。它打开一个 linux 套接字,您必须使用支持该套接字通信模式的驱动程序/库。这里的优点是通过内置连接器对数据库通信进行加密。

    注意:使用 Cloud SQL 公共 IP 时,请避免访问 Cloud SQL 数据库上的授权网络,以保持良好的安全性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2016-04-25
      • 2019-04-30
      • 1970-01-01
      相关资源
      最近更新 更多