dsozqcx9668 2018-03-02 02:30
浏览 181
已采纳

在这种情况下使用Redis池的正确方法

I am currently using the redigo library for my project where i create a redis pool

I use defer to release the redis connection every time i get one from the pool

c := redisPool.Get()
defer c.Close()

But it will block forever in this scenario if MaxActive has been set

func function1() {
  c := redisPool.Get()
  defer c.Close()

  function2()

  ...

}

func function2() {
  c := redisPool.Get()
  defer c.Close()
  ...
}  

should i use only one redis connection in one goroutine?

  • 写回答

2条回答 默认 最新

  • doujian7132 2018-03-02 03:27
    关注

    You have a few options here.

    1. You can Close() when you are done, returning the connection to the pool and then calling function2. Upside: works, not too complex. Downside: management of returning the connection in the case of multiple exit points from the function.

    2. You can change function2 to take a redis.Conn argument that it uses and just pass that connection off. Upside: defer still works for function1. Downside: you need a connection to call function2 and need to do connection management from the calling site. In your example that is easy enough.

    3. Make sure you have at least N*2 max connections, where N is the max number of concurrent goroutines that will be running. Upside: Your code stays as-is without changes. Downside: limited in the number of concurrent calls to function1 you can make.

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

报告相同问题?

悬赏问题

  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置