You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Memcached存储Express会话:如何使用连接池?

Connect-Memcached Connection Pool Setup for Node/Express Apps

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:

  1. Use a load testing tool to simulate concurrent requests (e.g., ab or wrk):
    ab -n 100 -c 20 http://localhost:3000/ # 100 total requests, 20 concurrent
    
  2. Check active connections to Memcached with netstat (Linux/macOS):
    netstat -an | grep 11211
    
    You should now see the connection count approaching your configured poolSize.

Key Notes

  • Don't Overdo the Pool Size: Set poolSize based 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 poolSize limit. You won't see all pool connections immediately on app startup.
  • Check Client Version: Ensure you're using the official memcached npm package (not alternatives like memjs), as configuration parameters vary between packages.

内容的提问来源于stack exchange,提问作者Akshay Jindal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:59:33