PHP
Database Connection Pool - إدارة الاتصالات
تنفيذ متقدم لـ Connection Pooling يقلل overhead الاتصالات ويحسن الأداء بشكل كبير.
class ConnectionPool {
private array $pool = [];
private array $inUse = [];
private int $maxConnections;
private int $timeout;
private $connectionFactory;
public function __construct(
int $maxConnections = 10,
int $timeout = 30,
callable $connectionFactory = null
) {
$this->maxConnections = $maxConnections;
$this->timeout = $timeout;
$this->connectionFactory = $connectionFactory ?? function() {
return new PDO(
'mysql:host=localhost;dbname=test',
'user',
'pass',
[PDO::ATTR_PERSISTENT => true]
);
};
}
public function acquire(): PDO {
// Try to get from pool
if (!empty($this->pool)) {
$conn = array_pop($this->pool);
$this->inUse[] = $conn;
return $conn;
}
// Create new if under limit
if (count($this->inUse) < $this->maxConnections) {
$conn = ($this->connectionFactory)();
$this->inUse[] = $conn;
return $conn;
}
// Wait for available connection
$startTime = time();
while (empty($this->pool) && (time() - $startTime) < $this->timeout) {
usleep(100000); // 100ms
}
if (empty($this->pool)) {
throw new \RuntimeException('Connection pool timeout');
}
$conn = array_pop($this->pool);
$this->inUse[] = $conn;
return $conn;
}
public function release(PDO $connection): void {
$key = array_search($connection, $this->inUse, true);
if ($key !== false) {
unset($this->inUse[$key]);
$this->inUse = array_values($this->inUse);
// Reset connection state
$connection->exec('ROLLBACK');
$this->pool[] = $connection;
}
}
public function getStats(): array {
return [
'available' => count($this->pool),
'in_use' => count($this->inUse),
'total' => count($this->pool) + count($this->inUse),
'max' => $this->maxConnections
];
}
}
// Usage with try-finally
$pool = new ConnectionPool(10);
$conn = $pool->acquire();
try {
$stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([1]);
$result = $stmt->fetchAll();
} finally {
$pool->release($conn);
}
💡 مثال الاستخدام
استخدم Connection Pool لتحسين أداء قواعد البيانات، تقليل overhead، أو إدارة الموارد بكفاءة.
استخدام حر
هذا الكود متاح للاستخدام الحر. إذا كان لديك أسئلة أو تحتاج مساعدة، لا تتردد في التواصل معي.