V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
chogath
V2EX  ›  问与答

在 Node.js 中如何合理的调配某些通用实例对象?(如 Redis)

  •  1
     
  •   chogath · 2021-02-03 10:01:12 +08:00 · 622 次点击
    这是一个创建于 1180 天前的主题,其中的信息可能已经有所发展或是发生改变。

    一、模块导入的方式:

    // redis.ts
    
    export const redis = new ioRedis(options);
    
    // service.ts
    
    import { redis } from './redis'
    
    const func1 = async () => { await redis.get('demo') };
    

    二、egg.js app 全局属性:

    
    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 依赖注入

    // 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 条附言  ·  2021-03-16 12:34:35 +08:00
    自己已经解决,还是用的依赖注入。在启动时在 ioc 上下文中获取提供者

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

    ## end
    ##---------------------------------------------------------
    3 条回复    2021-02-03 11:48:18 +08:00
    chogath
        1
    chogath  
    OP
       2021-02-03 10:16:36 +08:00
    现在使用的开发框架是 ts + nest.js ,分成了 lib / modules 两层

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

    如果 modules 层中需要 公共组件,则通过模块引入的方式调用具体方法(如 logger.info
    optional
        2
    optional  
       2021-02-03 11:01:03 +08:00 via Android
    第一种其实也是依赖注入
    chogath
        3
    chogath  
    OP
       2021-02-03 11:48:18 +08:00
    @optional emm...
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3127 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:28 · PVG 21:28 · LAX 06:28 · JFK 09:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.