【问题标题】:Websockets and database object scopeWebsockets 和数据库对象范围
【发布时间】:2016-07-18 10:58:58
【问题描述】:

在下面的代码中,我希望从提要接收“订单”并将其存储在数据库中。

我知道只要收到数据就会调用类方法 marketEvent,因此我需要在这个函数中插入我的语句。

每次调用类方法时打开和关闭 db 连接效率低下,所以我试图打开连接并将 db 对象传递给 marketEvent。

我是 nodejs 和 web 套接字的新手,所以不知道如何将它们组合在一起。

var pg = require("pg")
var conString = "postgres://myusername:mypassword@localhost/poloniex";
var client = new pg.Client(conString);


var autobahn = require('autobahn');
var wsuri = "wss://api.poloniex.com";
var connection = new autobahn.Connection({
    url: wsuri,
    realm: "realm1"
});

connection.onopen = function (session) {
    function marketEvent (args,kwargs) {
        client.query("INSERT INTO orderbook(order) values($1)", [args]);
    }
    session.subscribe('BTC_XMR', marketEvent);

}

connection.onclose = function () {
    console.log("Websocket connection closed");
}


client.connect();
connection.open();

【问题讨论】:

    标签: node.js postgresql autobahn


    【解决方案1】:

    我不知道“pg”和“autobahn”两者。但是从“pg”包的文档中,我可以为您提供一个解决方案的提示

    client.connect() 并不是一个孤立的调用。它需要一个函数委托来执行操作。

    connection.onopen = function (session) {
        function marketEvent (args,kwargs) {
            client.connect(function(err) {
                if (err) throw err;
                client.query("INSERT ...", [args]);
            });
        }
        session.subscribe('BTC_XMR', marketEvent);
    
    }
    

    关于有效使用连接,我猜你可能会要求池化。

    var pool = new pg.Pool(config);
    pool.connect(function(err, client, done) {
        if (err) throw err;
        client.query('INSERT ...', function(err, result) {
            //call `done()` to release the client back to the pool 
            done();
        });
    });
    

    请参阅此建议的原始来源以了解确切用法: https://www.npmjs.com/package/pg

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多