Node.js~ioredis處理耗時(shi)(shi)請(qing)求時(shi)(shi)連接數瀑增
關于(yu)redis連(lian)接數過高的解釋
對于node.js開(kai)發環境里,使用(yong)傳(chuan)統的(de)redis或者使用(yong)ioredis都是(shi)不錯(cuo)的(de)選擇(ze),而在處理大數(shu)據請求程中,偶(ou)爾出現(xian)了連接池( redis服務端的(de)最大可用(yong)連接數(shu),默認為1萬)不夠用(yong)的(de)情況(kuang),一般的(de)提(ti)示如下:
It was not possible to connect to the redis server(s); to create a disconnected multiplexer, disable AbortOnConnectFail
在redis-cli上(shang)輸(shu)入(ru)info命令(ling)也可以進行查看

redis-server.conf里配置了它默認(ren)的最大連接數
maxclients 10000
產生(sheng)它的原因(yin)有幾個:
- 單個請求使用結果后,沒有釋放,client.end()沒有使用,這主要是redis組件
- 而使用了ioredis組件后,需要redis會自動釋放,但時機也是http請求結束之后才執行,所以對于長時間沒有響應的請求,也會出現占用redis線程的問題,解決方法手動使用redis.quit()即可
- 單個請求時間過長,導師redis連接一直被一個請求占用,而在請求數過多時,這種現象就會引用連接池不夠用
- 多線程環境下(非node.js),使用了實例模塊,而沒有使用單例模式,因為很多redis驅動是支持多路復用的
大叔(shu)建議的作法:
減少單次請求的(de)響應時(shi)間,建(jian)議把redis從一(yi)個大請求中拿出來,因(yin)為(wei)純redis還是很快(kuai)的(de)
正確使用redis組件(jian),用完就關了
正確理解多線程與socket連接(jie),要知(zhi)道socket連接(jie)直接(jie)影響你的(de)服(fu)務器(qi)CPU性能
ioredis代(dai)碼實(shi)例
ioredis是個好東西(xi),它完全(quan)支(zhi)持了redis的cluster,sentinal等新(xin)技術
new Redis() // Connect to 127.0.0.1:6379 new Redis(6380) // 127.0.0.1:6380 new Redis(6379, '192.168.1.1') // 192.168.1.1:6379 new Redis('/tmp/redis.sock') new Redis({ port: 6379, // Redis port host: '127.0.0.1', // Redis host family: 4, // 4 (IPv4) or 6 (IPv6) password: 'auth', db: 0 })
同(tong)時支持標準的字(zi)符連接串
// Connect to 127.0.0.1:6380, db 4, using password "authpassword": new Redis('redis://:authpassword@127.0.0.1:6380/4')
支持(chi)發布與訂閱,它會存儲在進程(cheng)里,它不會被(bei)持(chi)久化,所有(you)會有(you)消(xiao)息丟失的情況(kuang)
var Redis = require('ioredis'); var redis = new Redis(); var pub = new Redis(); redis.subscribe('news', 'music', function (err, count) { // Now we are subscribed to both the 'news' and 'music' channels. // `count` represents the number of channels we are currently subscribed to. pub.publish('news', 'Hello world!'); pub.publish('music', 'Hello again!'); });
好了,下(xia)次我們有時間(jian)去講講ioredis的具體(ti)操作!
感謝各位的閱讀!