Egg: addSingleton 方法只能挂在在 mysql 上才能生效

Created on 11 Mar 2017  ·  5Comments  ·  Source: eggjs/egg

  • Node Version: v7.7.1
  • Egg Version: 1.0.0-rc.2

想基于 egg 封装一个 egg-bookshelf 的插件,于是参考官方的 egg-mysql 进行封装,但是发现只要将 lib/mysql.js 下的 app.addSingleton('mysql', func) 中的第一个参数修改为其他的值,并且将插件的命名改为其他的值,如 “bookshelf”,在应用加载时就会自动跳过加载这个插件。也就是说,要使用addSingleton方法,必须插件名命名为 mysql,挂载参数也要为mysql 才可以让该插件生效。

另外很疑惑 egg-knex 插件里为什么也是挂在 mysql 上,很多地方也直接用 mysql 作为变量名定义,毕竟 knex 支持很多类型的数据库,应该可以更通用一些。

question

Most helpful comment

通过 config.xxx.js 配置的时候,需要使用 client / clients 的方式;

源码参考:https://github.com/eggjs/egg/blob/master/lib/core/singleton.js#L25
配置参考:

config.redis = {
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
  },
}

All 5 comments

可以先看看文档 https://eggjs.org/zh-cn/advanced/plugin.html#全局实例插件的最佳实践

egg-redis 也是这样实现的,不存在只能挂载 mysql 的问题。

@dead-horse 我这边也遇到了相同的问题,没太看懂。

image

简单基于 repo-utils/node-gitlab 写了个 插件,然后图中 红色框住的部分 不会执行,没框住的能正常执行

通过 config.xxx.js 配置的时候,需要使用 client / clients 的方式;

源码参考:https://github.com/eggjs/egg/blob/master/lib/core/singleton.js#L25
配置参考:

config.redis = {
  client: {
    port: 6379,          // Redis port
    host: '127.0.0.1',   // Redis host
    password: 'auth',
    db: 0,
  },
}

明白了。。config 里 要有 client。。

真坑

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dizhifeng picture dizhifeng  ·  3Comments

yuu2lee4 picture yuu2lee4  ·  3Comments

Seovos picture Seovos  ·  3Comments

lvgg3271 picture lvgg3271  ·  3Comments

Webjiacheng picture Webjiacheng  ·  3Comments