热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Node.js中高效管理和优化通用实例对象(如Redis)的使用?

一、模块导入的方式:123456789// redis.tsexport const redis = new ioRedis(options);// service.tsimport { redis


一、模块导入的方式:



1
2
3
4
5
6
7
8
9
// redis.ts



export const redis = new ioRedis(options);



// service.ts



import { redis } from './redis'



const func1 = async () => { await redis.get('demo') };



二、egg.js app 全局属性:

1
2
3
4
5
6
module.exports.login = function* (ctx) {

    const {app} = this

    const form = ctx.request.body

    let time = 3600 * 24 * 30 //token 过期时间

    let token = generateToken({_id: form._id}, time)// 生成 token

    app.redis.set(form.username, token) // 把 token 存入 redis



三、Nest.js 依赖注入



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// redis.ts



export const redisProviders = {

    provide: 'redis',

    useFactory: async () => {

    redis = new ioRedis(options);

    return redis;

    },

};



@Module({

  providers: [redisProviders],

  exports: [redisProviders],

})

export class RedisModule {}



// service.ts



@Injectable()

export class Service {

  constructor(

    @Inject('redis')

    private readonly redis

  ) {}



  async func1() {

    await this.redis.get('demo')

  }

}



个人倾向于第三种,但是在实际的开发中用的是第一种。按另一个例子 logger 实例来说,logger 有 info / error 等方法来记录日志,在全局启动的时候,也需要 logger 实例,这种情况依赖注入的方式反而成为一种限制。

Node.js 后端开发经验有限,请大家指正。

第 1 条附言  ·  19 天前

自己已经解决,还是用的依赖注入。在启动时在 ioc 上下文中获取提供者

## 以下是我自己认为的最佳实践
##---------------------------------------------------------
https://github.com/sophons-space/nest-server
https://github.com/sophons-space/nest-gateway
https://github.com/sophons-space/nest-user-center

## end
##---------------------------------------------------------

现在使用的开发框架是 ts + nest.js ,分成了 lib / modules 两层

lib 用来定义一些公共组件,如 redis 、database 、logger 等。
modules 用来实现业务,其中 controller 、service 、dao 使用的是依赖注入。

如果 modules 层中需要 公共组件,则通过模块引入的方式调用具体方法(如 logger.info )


   



推荐阅读
author-avatar
真理难辩_175
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有