# pymongo.errors.ServerSelectionTimeoutError：连接已关闭，超时：30秒

- **ID:** `database/mongodb-connection-pool-timeout`
- **领域:** database
- **类别:** connection_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

当连接池中的所有连接都已关闭或耗尽时，MongoDB 驱动程序的服务器选择超时发生，通常由网络中断、服务器过载或应用程序中的连接池配置错误引起。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| MongoDB 5.0 | active | — | — |
| MongoDB 6.0 | active | — | — |
| MongoDB 7.0 | active | — | — |

## 解决方案

1. ```
   Set MongoClient options: client = MongoClient('mongodb://localhost:27017', maxPoolSize=50, minPoolSize=10, retryWrites=True, retryReads=True). This ensures connections are maintained and operations retry on failure.
   ```
2. ```
   Use MongoDB drivers' built-in heartbeat monitoring: MongoClient('mongodb://localhost:27017', heartbeatFrequencyMS=10000). This detects closed connections and reconnects automatically.
   ```
3. ```
   Wrap database calls in a retry decorator: import time; from pymongo.errors import ServerSelectionTimeoutError; def retry_on_timeout(func): for attempt in range(3): try: return func() except ServerSelectionTimeoutError: time.sleep(2**attempt); raise.
   ```

## 无效尝试

- **** — This only delays failure; if connections are genuinely closed, the timeout will eventually trigger anyway, and the application remains unresponsive longer. (90% 失败率)
- **** — The same configuration or network problem persists; the error will reappear shortly after restart. (95% 失败率)
- **** — This prevents connection reuse, causing new connections for every operation, which increases latency and may exhaust server resources. (70% 失败率)
