dragon_9000 2018-02-27 05:37
浏览 82
已采纳

如何在多个程序包之间共享单个数据库连接

I have two packages named client and worker. I want to share same ssdb, mysql and redis connection with both the packages. One more similar problem that i am facing to share auth between these two packages.

app
  -> client pkg
  -> worker pkg
  main.go (contains auth as global variable)

Can anyone please suggest me the best way to implement these two things ?

  • 写回答

2条回答 默认 最新

  • doukun8670 2018-02-27 07:15
    关注

    There's lots of ways to do this and each approach has pros and cons and it really depends on what you are doing. One easy way to do this is to have a third package with the DB connection and import it from the other two packages and from the main package.

    app
      -> client pkg // import "app/global"
      -> worker pkg // import "app/global"
      -> global pkg // Contains ssdb and auth as global variables
      main.go
    

    Another approach that might be better depending on what you are doing is to have the functions on the client and worker packages accept a db connection as a parameter and from main.go initialize the db and pass it as a parameter when you call a function that needs it.

    It depends on what you are doing but for big projects it's easier to maintain if you just have one package doing all your db operations and you access it from all the places you need to do something. That way you don't have to worry about this issue because only one package has to worry about the db connection even if several packages use it.

    Edit:

    The problem with global variables is that they can be modified at the same time from everywhere in your project and it can introduce race conditions, but there is nothing wrong in using them when this is not an issue.

    In this case, you are just setting the value once, when you connect to the DB and then just use the object.

    You mentioned you want to have another package for the auth, I recommend just having one package and having in it everything you need to access from more than one package, in this case ssdb and auth.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功