我应该在文件/模块之间共享 Redis 连接吗? [英] Should I share Redis connection between files/modules?

查看:52
本文介绍了我应该在文件/模块之间共享 Redis 连接吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 node.js 应用程序,我需要大量使用 Redis.该应用程序将在 8 个 CPU 内核上集群ed.

I'm developing a node.js app and I am in need of heavy Redis usage. The app will be clustered across 8 CPU cores.

现在我有 100 个到 Redis 的并发连接,因为每个 CPU 的每个 worker 都有几个运行 require('redis').createClient() 的模块.

Right now I have 100 concurrent connections to Redis because every worker per CPU has several modules running require('redis').createClient().

场景 A:

file1.js:

var redis = require('redis').createClient();

file2.js

var redis = require('redis').createClient();

场景 B:

redis.js

var redis = require('redis').createClient();

module.exports = redis;

file1.js

var redis = require('./redis');

file2.js

var redis = require('./redis');

哪种方法更好:在我引入的每个新文件中创建新的 Redis 实例(场景 A)或全局创建一个 Redis 连接(场景 B)并在我拥有的所有模块之间共享此连接.每种解决方案的缺点/优点是什么?

Which approach is better: creating new Redis instance in every new file I introduce (scenario A) or creating one Redis connection globally (scenario B) and sharing this connection across all modules I have. What are drawbacks/benefits of each solution?

提前致谢!

推荐答案

当我遇到这样的问题时,我通常会考虑三个基本问题.

When I face a question such as this I generally think about three basic questions.

  1. 哪个更易读?
  2. 哪个可以更好地重用代码?
  3. 哪个更有效?

不一定按这个顺序,因为它取决于场景,但我相信在这种情况下,所有三个问题都支持选项 B.如果您需要修改 createClient 的选项,则需要在使用它的每个文件中编辑它们.其中选项 A 是每个使用 redis 的文件,选项 B 只是 redis.js.此外,如果出现更新或不同的产品并且您想要替换 redis,那么将 redis.js 用作不同包甚至更新的 redis 客户端的包装器是可行的,从而大大减少转换时间.

Not necessarily in this order as it depends on the scenario, but I believe in this case all three of these questions are in favor of option B. If you ever needed to modify options for createClient, you would then need to edit them in every file which uses it. Which in option A is every file which uses redis, and option B is just redis.js. Also if a newer or different product comes out and you want to replace redis It would be feasible to make redis.js a wrapper for a different package or even a newer redis client substantially cutting down conversion time.

全局通常是坏事,但在这个例子中 redis.js 不应该存储可变状态,所以在这种情况下有一个全局/单例是没有问题的.

Globals are generally a bad thing, but in this example redis.js should not be storing mutable state, so there is no problem having a global/singleton in this context.

这篇关于我应该在文件/模块之间共享 Redis 连接吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆