首页 > 解决方案 > 如何通过套接字传递 Postgres 池或客户端

问题描述

因此,我已将我的服务器部署到 Heroku,并使用以下内容:

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
});
const http = require('http').Server(app);
const io = require('socket.io')(http);

我有一个函数向我的 Raspberry Pi(在本例中充当套接字客户端)发送请求,要求它运行抓取功能并相应地更新 Heroku Postgres 数据库中的表。唯一的问题是在 Pi 上,client.query() 函数无法识别......不知道为什么。这是我将请求发送到 Pi 的函数:

async function F1() {
  const client = await pool.connect();
  try {
    await client.query('BEGIN')
    //do some database updating here in some table updates
    
    let date = ("0" + terminationTime.getDate()).slice(-2);
    let month = ("0" + (terminationTime.getMonth() + 1)).slice(-2);
    let year = terminationTime.getFullYear();
    let hours = terminationTime.getHours();
    let minutes = terminationTime.getMinutes();
    let seconds = terminationTime.getSeconds();
    let timestamp = year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds
    let data = {
        pool: pool, //here I tried passing in the pool, also tried passing in client
        query: query,
        timestamp: timestamp
      }
      io.to(RPiMiniServerID).emit("requestToPi", data)
  } catch(err) {
    console.log(err);
  }
}

这是我在 Pi/Client 端的代码:

const io = require("socket.io-client");
const socket = io.connect("MY HEROKU APP URL HERE")
const { Pool, Client } = require("pg");

socket.on("requestToPi", (data) => sync function() {
  let client = await data.pool.connect()
  let query = data.query
  let timestamp = data.timestamp
  //a bunch more code and THEN
  await client.query('INSERT INTO table (columnnames) VALUES($1)', [value]); //this is the line with the error
}()); 

我试过直接传入客户端,但这也行不通。不太确定在这里做什么 - 非常感谢任何帮助!

标签: javascriptnode.jspostgresqlsocketssocket.io

解决方案


让我直截了当地说,您正在尝试将pg在您的 heroku 服务器上启动的库对象的实例发送到您的 Pi 并从该“pg”库对象状态继续操作?

HTTP 的第一条规则是它是无状态的。我知道它的 Socket io,但它仍然依赖于 http,并且在另一端重新创建数据,并且它的状态通过连接丢失。因此,在某种程度上,您正在 Pi 上启动实例的新实例,pg而 heroku 服务器上的实例与 Pi 上的实例不同。

  await client.query('INSERT INTO table (columnnames) VALUES($1)', [value]); //this is the line with the error

那是因为数据已经完全失去了它的状态。这意味着,你没有连接到数据库,你还没有开始提交过程,等等。pg你手头上有一个新的库实例,你在 heroku 服务器上所做的一切都完全不同。

这个问题的一个解决方案是使用某种实时模型数据同步,如主干网或其他类似的解决方案。


推荐阅读