redigo提示connection pool exhausted
版权声明 本站原创文章 由 萌叔 发表
转载请注明 萌叔 | https://vearne.cc
1. 引言
线上的某个服务(Golang开发)使用Redis作为消息队列,使用的redis库是garyburd/redigo, 这两天出现如下错误
connection pool exhausted
2. 产生原因
阅读源码pool.go 阅读get()即可
type Pool struct {
// Dial()方法返回一个连接,从在需要创建连接到的时候调用
Dial func() (Conn, error)
// TestOnBorrow()方法是一个可选项,该方法用来诊断一个连接的健康状态
TestOnBorrow func(c Conn, t time.Time) error
// 最大空闲连接数
MaxIdle int
// 一个pool所能分配的最大的连接数目
// 当设置成0的时候,该pool连接数没有限制
MaxActive int
// 空闲连接超时时间,超过超时时间的空闲连接会被关闭。
// 如果设置成0,空闲连接将不会被关闭
// 应该设置一个比redis服务端超时时间更短的时间
IdleTimeout time.Duration
// 如果Wait被设置成true,则Get()方法将会阻塞
Wait bool
... ...
}
以上异常的原因是这样的,在garyburd/redigo中,得到连接的步骤如下
1. 尝试从空闲列表中,获得一个可用连接;如果成功直接返回,失败则尝试步骤2
2. 如果当前的Active 连接数 < MaxActive,则尝试创建一个新连接;如果成功直接返回,失败则尝试步骤3
3. 判断Wait为true则等待,否则报出异常
// ErrPoolExhausted is returned from a pool connection method (Do, Send,
// Receive, Flush, Err) when the maximum number of database connections in the
// pool has been reached.
var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
3. 解决方法
- 1) 设置MaxActive,设MaxActive=0(表示无限大)或者足够大。
- 2) 设置Wait=true,当程序执行get(),无法获得可用连接时,将会暂时阻塞。
4. 完整的初始化连接池的代码
func NewRedisPool(redisConf context.RedisConf) *redis.Pool {
address := fmt.Sprintf("%v:%v", redisConf.Host, redisConf.Port)
dbOption := redis.DialDatabase(redisConf.Db)
pwOption := redis.DialPassword(redisConf.Password)
// **重要** 设置读写超时
readTimeout := redis.DialReadTimeout(time.Second * time.Duration(redisConf.ConTimeout))
writeTimeout := redis.DialWriteTimeout(time.Second * time.Duration(redisConf.ConTimeout))
conTimeout := redis.DialConnectTimeout(time.Second * time.Duration(redisConf.ConTimeout))
redisPool := &redis.Pool{
// 从配置文件获取maxidle以及maxactive,取不到则用后面的默认值
MaxIdle: redisConf.MaxIdleConn,
MaxActive: redisConf.MaxActiveConn,
// **重要** 如果空闲列表中没有可用的连接
// 且当前Active连接数 < MaxActive
// 则等待
Wait: true,
IdleTimeout: time.Duration(redisConf.IdleTimeout) * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", address, dbOption, pwOption,
readTimeout, writeTimeout, conTimeout)
if err != nil {
return nil, err
}
return c, nil
},
}
return redisPool
}
On this platform, you can discover lots of online slots from famous studios.
Visitors can try out traditional machines as well as feature-packed games with vivid animation and interactive gameplay.
If you’re just starting out or an experienced player, there’s always a slot to match your mood.
money casino
The games are available 24/7 and designed for PCs and mobile devices alike.
All games run in your browser, so you can jump into the action right away.
Site navigation is user-friendly, making it quick to explore new games.
Join the fun, and discover the excitement of spinning reels!
Наличие страховки во время путешествия — это важный шаг для финансовой защиты туриста.
Документ обеспечивает медицинскую помощь в случае несчастного случая за границей.
К тому же, документ может обеспечивать оплату на возвращение домой.
merk-kirov.ru
Некоторые государства предусматривают предоставление документа для получения визы.
Без наличия документа обращение к врачу могут привести к большим затратам.
Оформление полиса заблаговременно
Наша платформа — настоящий онлайн-магазин Боттега Вэнета с доставкой по территории России.
В нашем магазине вы можете приобрести оригинальные товары Боттега Венета с гарантией подлинности.
Каждый заказ подтверждены сертификатами от бренда.
bottega-official.ru
Доставление осуществляется без задержек в любой регион России.
Интернет-магазин предлагает выгодные условия покупки и комфортные условия возврата.
Выбирайте официальном сайте Bottega Veneta, чтобы получить безупречный сервис!
On this site, you can find trusted platforms for CS:GO gambling.
We have collected a variety of wagering platforms centered around Counter-Strike: Global Offensive.
Each site is carefully selected to secure reliability.
csgo casino slots
Whether you’re a seasoned bettor, you’ll easily select a platform that matches your preferences.
Our goal is to help you to connect with proven CS:GO wagering platforms.
Start browsing our list right away and upgrade your CS:GO betting experience!
Questo sito offre l’ingaggio di operatori per compiti delicati.
Chi cerca aiuto possono scegliere operatori competenti per incarichi occasionali.
Le persone disponibili vengono verificati con cura.
assumi assassino
Sul sito è possibile ottenere informazioni dettagliate prima di assumere.
La sicurezza è la nostra priorità.
Esplorate le offerte oggi stesso per portare a termine il vostro progetto!
Il nostro servizio rende possibile il reclutamento di operatori per lavori pericolosi.
Chi cerca aiuto possono scegliere candidati qualificati per operazioni isolate.
Gli operatori proposti vengono scelti con severi controlli.
ordina omicidio l’uccisione
Con il nostro aiuto è possibile visualizzare profili prima della selezione.
La professionalità resta al centro del nostro servizio.
Contattateci oggi stesso per ottenere aiuto specializzato!
Here, you can discover a great variety of online slots from leading developers.
Visitors can try out classic slots as well as modern video slots with vivid animation and bonus rounds.
Whether you’re a beginner or a seasoned gamer, there’s always a slot to match your mood.
casino games
The games are available 24/7 and designed for desktop computers and mobile devices alike.
No download is required, so you can jump into the action right away.
The interface is intuitive, making it simple to explore new games.
Register now, and dive into the excitement of spinning reels!
Get a massive 200% bonus on your first deposit and boost your starting balance up to $ 200. betwinner register, Betwinner splits your bonus between sports and games to double your chances of winning.
Searching for a person to handle a rare hazardous task?
Our platform focuses on connecting clients with workers who are ready to execute critical jobs.
If you’re dealing with emergency repairs, hazardous cleanups, or risky installations, you’ve come to the right place.
Every listed professional is pre-screened and qualified to ensure your security.
hire an assassin
This service provide transparent pricing, comprehensive profiles, and safe payment methods.
No matter how difficult the scenario, our network has the expertise to get it done.
Start your search today and find the perfect candidate for your needs.
The platform offers valuable information about ways of becoming a digital intruder.
Facts are conveyed in a transparent and lucid manner.
You will learn different tactics for penetrating networks.
Besides, there are practical examples that manifest how to utilize these abilities.
how to become a hacker
Whole material is constantly revised to correspond to the modern innovations in cybersecurity.
Distinct concentration is concentrated on workable execution of the gained expertise.
Be aware that all operations should be utilized ethically and through ethical means only.
This site you can get access to special discount codes for one of the leading betting services.
The range of enticing deals is continuously improved to ensure that you always have means to utilize the current opportunities.
Via these coupons, you can save a lot on your betting endeavors and improve your probability of triumph.
Every coupon are thoroughly verified for validity and efficiency before showing up.
https://franceslargemanroth.com/blog/ruka_ubiyca_1999_opisanie.html
What’s more, we present extensive details on how to utilize each promo code to optimize your gains.
Remember that some opportunities may have special provisions or expiration dates, so it’s fundamental to review attentively all the specifications before applying them.
Our website is available valuable promo codes for One X Bet.
Such codes provide an opportunity to obtain bonus incentives when playing on the website.
Every listed promotional codes are always up-to-date to maintain their usability.
With these codes there is an opportunity to boost your chances on 1xBet.
https://retmgen.org/wp-content/pgs/mashinnoe_oshtukaturivanie_skorosty_i_kachestvo.html
Moreover, comprehensive manuals on how to use special offers are available for maximum efficiency.
Note that some promocodes may have particular conditions, so examine rules before redeeming.
Hello to our platform, where you can discover exclusive content created exclusively for adults.
All the resources available here is intended only for individuals who are 18 years old or above.
Ensure that you are eligible before proceeding.
mature video
Experience a one-of-a-kind selection of adult-only content, and dive in today!