簡體   English   中英

在 nodejs 中使用 redis 的最佳實踐是什么?

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

我正在使用 nodejs、express 和node_redis構建一個應用程序。 我想制作一個模塊來封裝所有與redis相關的操作,這樣我就不必到處處理redis key。

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

那么我在這里有兩個問題。

  1. 我想創建redis連接並選擇一個數據庫:

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

    由於select是一個異步調用,我如何在單獨的模塊 ( db.js ) 中使用它?

  2. 看起來client.quite()必須在腳本結束之前調用,否則腳本不會退出。 client被封裝為db.js的局部變量時,我怎么能在db.js之外做到這db.js

我建議使用定義的接口制作類似服務/存儲庫/接口的東西,然后調用它的方法。

例如,如果您有一個用戶數據庫:

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

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

UserService.prototype.... so on

現在,在您的 Express 應用程序中,您將創建一個 UserService 變量並使用它。 當然,您應該更智能地創建 UserService。 在 UserService 中,您可以添加緩存。

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

結束閱讀: 我需要退出嗎

我用這個

庫/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;

索引.js

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

這只會創建一個連接,因此您只會得到:

Redis 連接已創建

代替

Redis 連接已創建

Redis 連接已創建

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM