我正在使用Node的Express w/Connect中间件.Connect的内存会话存储不适合生产:

Warning: connection.session() MemoryStore is not designed for a production environment, as it will leak memory, and obviously only work within a single process.

对于更大的部署,mongo或redis是有意义的.

但是,对于生产中的单主机应用程序,什么是好的解决方案呢?

推荐答案

花了一天的时间调查这件事.以下是我发现的选项.每秒的请求通过本地机器上的ab -n 100000 -c 1 http://127.0.0.1:9778/执行.

  • 无会话-快速(438请求/秒)
  • cookieSession:不需要外部服务,速度影响较小(311请求/秒)-最快,会话将随着cookie过期(由maxAge定制)
  • connect-redis:需要redis服务器,速度影响大(使用redis2go和redisgreen时每秒4个请求)-比mongo更快,会话将在一段时间后被删除(由ttl定制)
  • connect-mongo-需要mongodb服务器,速度影响大(mongohq为2 req/sec)-比redis慢,需要将manual clear_interval设置为清理会话

以下是我在cookieSession上使用的咖啡脚本:

server.use express.cookieSession({
    secret: appConfig.site.salt
    cookie: maxAge: 1000*60*60
})

以下是我为redis使用的咖啡脚本:

RedisSessionStore ?= require('connect-redis')(express)
redisSessionStore ?= new RedisSessionStore(
    host: appConfig.databaseRedis.host
    port: appConfig.databaseRedis.port
    db: appConfig.databaseRedis.username
    pass: appConfig.databaseRedis.password
    no_ready_check: true
    ttl: 60*60  # hour
)
server.use express.session({
    secret: appConfig.site.salt
    cookie: maxAge: 1000*60*60
    store: redisSessionStore
})

以下是我为mongo准备的咖啡脚本:

server.use express.session({
    secret: appConfig.site.salt
    cookie:
        maxAge: 100*60*60
    store: new MongoSessionStore({
        db: appConfig.database.name
        host: appConfig.database.host
        port: appConfig.database.port
        username: appConfig.database.username
        password: appConfig.database.password
        auto_reconnect: appConfig.database.serverOptions.auto_reconnect
        clear_interval: 60*60  # hour
    })
})

当然,远程redis和mongo数据库的运行速度将比本地同类数据库慢.I just couldn't get the local equivalents working, especially considering the installation and maintenance time for me was far more than what I was willing to invest when compared with hosted remote alternatives, something I feel is true for others too hence why these hosted remote database services exist in the first place!

有关本地数据库benhmarks,请参见@Mustafa's answer.

很高兴有人到了edit this answer岁,可以将本地数据库基准添加到这个组合中.

Node.js相关问答推荐

我的Node.js应用程序没有将Mongoose方法findByIdAndDelete作为函数进行检测

未显示NPM版本

Axios TypeError:将循环 struct 转换为 JSON

Prisma 和 Nextjs:重新部署之前内容不会更新

Solidity 将数据位置从内存更改为存储

Docker node_modules 文件夹上的 React 应用程序不可用

错误:无法为 /blog 收集页面数据并且在 object.fetch 处获取失败

每秒从套接字传来的数据有哪些存储方式?

React Native:执行 com.android.build.gradle.internal.tasks.Workers$ActionFacade 时发生故障

Express.js cookie setter 的 Domain 属性:如何与 *多个 * 域共享 cookie?

为什么我的react 表单不能正常工作?

无法通过谷歌Electron 表格 api( node js)中的服务帐户访问写入

node.js 中 res.setHeader 和 res.header 的区别

如何正确使用 package.json 中的关键字属性?

Node.js 变量声明和范围

等价于 Node.js 的 Rails 控制台

Puppeteer 错误:未下载 Chromium 修订版

如何将`yarn.lock`与`package.json`同步?

Route.get() 需要回调函数,但得到对象未定义

在 react-router v4 中使用 React IndexRoute