简体   繁体   English

在 nodejs 中使用 redis 的最佳实践是什么?

[英]What is the best practice for using redis in nodejs?

I'm building an app with nodejs, express and node_redis .我正在使用 nodejs、express 和node_redis构建一个应用程序。 I want to make a module to encapsule all the redis-related operations so that I don't have to deal with redis keys everywhere.我想制作一个模块来封装所有与redis相关的操作,这样我就不必到处处理redis key。

|- app.js
|- models
|   |- db.js   <-- All redis-related operations here
.....

Then I have two problems here.那么我在这里有两个问题。

  1. I want to create the redis connection and select a database:我想创建redis连接并选择一个数据库:

     var redis = require('redis'); var client = redis.createClient(); client.select(config.database, function() { // actual db code });

    Since select is an async call, how could I use it in a separate module ( db.js )?由于select是一个异步调用,我如何在单独的模块 ( db.js ) 中使用它?

  2. Looks like client.quite() must be called before the script ends, or the script won't quit.看起来client.quite()必须在脚本结束之前调用,否则脚本不会退出。 How could I do this outside db.js while client is encapsuled as a local variable in db.js ?client被封装为db.js的局部变量时,我怎么能在db.js之外做到这db.js

I suggest to make something like a service/repository/interface with a defined interface, then call it's methods.我建议使用定义的接口制作类似服务/存储库/接口的东西,然后调用它的方法。

For example, if you have a users db:例如,如果您有一个用户数据库:

var UserService=function(){
  this.client=new ...
}

UserService.prototype.getUserById=function(id, cb){
this.client.select(...,function(result,err){
  cb(result);
}
}

UserService.prototype.... so on

Now in your express app you will create an UserService var and use it.现在,在您的 Express 应用程序中,您将创建一个 UserService 变量并使用它。 Of course, you should create UserService smarter.当然,您应该更智能地创建 UserService。 In UserService, then you can add cache.在 UserService 中,您可以添加缓存。

var app = express();
var userService = new UserService();
//...

For closing read this: Do I need to quit结束阅读: 我需要退出吗

I use this我用这个

lib/redisClient.js库/redisClient.js

import redis from "redis";

let _redisClient;

const redisClient = {
  createClient(uri)  {
    if (!_redisClient){
      console.log('Redis conexion created')
    _redisClient = redis.createClient(uri);
    }
    return _redisClient;
  },
  close(): void {
    _redisClient.close();
  }
};

export default redisClient;

index.js索引.js

import redisClient from "./lib/RedisClient"
...
const client = redisClient.createClient(process.env.REDISURI)
const clientA = redisClient.createClient(process.env.REDISURI)
...

And this only creates one connexion so you only get:这只会创建一个连接,因此您只会得到:

Redis connexion created Redis 连接已创建

Instead of代替

Redis connexion created Redis 连接已创建

Redis connexion created Redis 连接已创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM