← Back to Node.js Course | Chapter 9: Database Integration | Lesson 4 of 7

Connection Pooling क्या है

एक pool प्रति request एक नया खोलने की बजाय reuse के लिए ready open database connections का एक set रखता है।

In this page:

  1. Connection Pooling
Syntax
javascript
const pool = mysql.createPool({ host: 'host', user: 'user', database: 'database', connectionLimit: n });
const [rows] = await pool.query('SQL', [values]);

Connection Pooling

Connections खोलना slow है, इसलिए pools idle वाले hand out करते हैं और release होने पर इन्हें वापस लेते हैं। आप एक maximum size set करते हैं। जब सारे connections busy हों requests wait करती हैं। जो connections आप check out करते हैं उन्हें हमेशा release करें।

Note: अपने database की connection limit के लिए pool size करें।

उदाहरण: Connection pooling

javascript
class Pool {
  constructor(max) { this.max = max; this.inUse = 0; this.waiting = []; }
  async acquire() {
    if (this.inUse < this.max) { this.inUse++; return; }
    await new Promise((r) => this.waiting.push(r));
  }
  release() {
    const next = this.waiting.shift();
    if (next) next(); else this.inUse--;
  }
}
const pool = new Pool(2);
(async () => {
  const job = async (n) => { await pool.acquire(); console.log("job", n, "running, inUse:", pool.inUse); await new Promise((r) => setTimeout(r, 5)); pool.release(); };
  await Promise.all([job(1), job(2), job(3)]);
  console.log("all done, inUse:", pool.inUse);
})();

// Output:
// job 1 running, inUse: 2
// job 2 running, inUse: 2
// job 3 running, inUse: 2
// all done, inUse: 0

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. connections release न करना
  2. pool को बहुत बड़ा बनाना
  3. प्रति request एक नया pool बनाना
चैप्टर सारांश
  • Pools connections reuse करते हैं
  • एक maximum size set करें
  • हमेशा release करें
  • प्रति app एक pool
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.