基于Memcached存储Express会话:如何使用连接池?
Hey there! Let's figure out why you're only seeing 2 connections to your Memcached server and how to properly implement a connection pool with connect-memcached.
The Root of the Issue
By default, the underlying memcached client that connect-memcached relies on has a tiny default connection pool size (often just 2). Unless you explicitly configure it to use more connections, it won't scale up even under load. The good news is we can fix this by manually creating a Memcached client with custom pool settings and passing it to connect-memcached.
Step-by-Step Implementation
1. Ensure Dependencies are Installed
First, make sure you have all required packages in place:
npm install express express-session memcached connect-memcached
2. Configure a Custom Memcached Client with Connection Pool
Instead of letting connect-memcached create a default client, we'll build our own with explicit pool size settings. Here's a complete code example:
const express = require('express'); const session = require('express-session'); const Memcached = require('memcached'); const MemcachedStore = require('connect-memcached')(session); // Create a Memcached client with connection pool configuration const memcachedClient = new Memcached('your-memcached-server:11211', { poolSize: 10, // Set your desired pool size here (adjust based on traffic needs) retries: 5, retry: 5000, remove: true // Automatically remove unresponsive servers from the pool }); // Initialize Express app const app = express(); // Configure session storage with our custom Memcached client app.use(session({ secret: 'your-strong-unique-secret-key', resave: false, saveUninitialized: false, store: new MemcachedStore({ client: memcachedClient, // Critical: use our pre-configured client prefix: 'app-sessions:' // Optional: prefix for session keys in Memcached }) })); // Test route to trigger session activity app.get('/', (req, res) => { req.session.user = { id: 1, name: 'Test User' }; res.send('Session stored successfully!'); }); app.listen(3000, () => { console.log('App running on http://localhost:3000'); });
3. Adjust Memcached Server's Maximum Connections
If you set a large poolSize, you need to make sure your Memcached server allows enough concurrent connections. By default, Memcached limits connections to 1024. To increase this, start Memcached with the -c flag:
memcached -c 2048 # Allows up to 2048 concurrent connections
4. Verify the Connection Pool is Working
To confirm more connections are being used:
- Use a load testing tool to simulate concurrent requests (e.g.,
aborwrk):ab -n 100 -c 20 http://localhost:3000/ # 100 total requests, 20 concurrent - Check active connections to Memcached with
netstat(Linux/macOS):
You should now see the connection count approaching your configurednetstat -an | grep 11211poolSize.
Key Notes
- Don't Overdo the Pool Size: Set
poolSizebased on your actual traffic and server resources. Too many connections can overwhelm Memcached. - Connection Pool is On-Demand: The client will only create new connections as needed, up to the
poolSizelimit. You won't see all pool connections immediately on app startup. - Check Client Version: Ensure you're using the official
memcachednpm package (not alternatives likememjs), as configuration parameters vary between packages.
内容的提问来源于stack exchange,提问作者Akshay Jindal

