0x001
V2EX  ›  Node.js

nodejs 如何实现单例

  •  
  •   0x001 · Jun 17, 2014 · 6921 views
    This topic created in 4525 days ago, the information mentioned may be changed or developed.
    比如我相保存我的mysql连接实例,我想保存在一个单例里,因为很多地方需要操作数据库。 这样就可以只需要连接一次。 不是每来一个请求去连接一次数据库。
    6 replies  •  2014-06-27 17:34:45 +08:00
    ipconfiger
    ipconfiger
    Jun 17, 2014
    1
    全局变量
    0x001
    0x001
    OP
    Jun 17, 2014
    2
    @ipconfiger 全局变量不太好,因为有好多变量的,我想存在一个统一的地方。
    kfll
    kfll
    Jun 17, 2014
    3
    # db.js

    var _con = null;

    function getConnection() {
    if (null === _con) _con = _connect();
    return _con;
    }

    function _connect() {
    // ...
    return xxxx;
    }

    exports.getConnection = getConnection;
    canesten
    canesten
    Jun 17, 2014
    4
    请使用连接池
    rekey
    rekey
    Jun 27, 2014
    6
    require 会缓存结果的,你可以直接初始化,然后 module.exports = 实例。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4943 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 07:33 · PVG 15:33 · LAX 23:33 · JFK 02:33
    ♥ Do have faith in what you're doing.