MongoPool.php
2.0 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
namespace jiaoyin;
use MongoDB\Client;
use Swoole\Coroutine;
use Swoole\Coroutine\Channel;
class MongoPool
{
private $pool;
private $maxSize;
private $currentSize;
private $mongoUri;
private $options;
public function __construct($mongoUri, $maxSize = 20, $options = [])
{
$this->mongoUri = $mongoUri;
$this->maxSize = $maxSize;
$this->currentSize = 0;
$this->options = $options;
$this->pool = new Channel($maxSize);
// 初始化连接池
for ($i = 0; $i < $maxSize; $i++) {
$this->pool->push($this->createConnection());
}
}
private function createConnection()
{
$manager = new Client($this->mongoUri, $this->options);
return $manager;
}
public function get()
{
while ($this->pool->isEmpty()) {
// output('Mongodb连接池为空,等待释放连接');
Coroutine::sleep(0.1);
}
$connection = $this->pool->pop();
if (!$connection) {
if ($this->currentSize < $this->maxSize) {
// 如果连接池未满,则创建新连接
$connection = $this->createConnection();
$this->currentSize++;
} else {
// 连接池已满,等待其他协程释放连接
$connection = $this->pool->pop();
}
}
return $connection;
}
public function push($connection)
{
// 检查连接是否有效,这里仅做示例,实际应用中可能需要更复杂的逻辑
if (is_object($connection) && get_class($connection) === Client::class) {
$this->pool->push($connection);
} else {
$this->currentSize -= 1;
}
}
public function close()
{
while (!$this->pool->isEmpty()) {
$connection = $this->pool->pop();
if (is_resource($connection)) {
$connection->close();
}
}
$this->currentSize = 0;
}
}