-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy path03-load-balancers.php
More file actions
207 lines (161 loc) · 6.55 KB
/
03-load-balancers.php
File metadata and controls
207 lines (161 loc) · 6.55 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php
/**
* Load Balancers Example
*
* Demonstrates different load balancing strategies for read replicas.
* Includes RoundRobin, Random, and Weighted load balancers.
*/
declare(strict_types=1);
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../helpers.php';
use tommyknocker\pdodb\PdoDb;
use tommyknocker\pdodb\connection\loadbalancer\RoundRobinLoadBalancer;
use tommyknocker\pdodb\connection\loadbalancer\RandomLoadBalancer;
use tommyknocker\pdodb\connection\loadbalancer\WeightedLoadBalancer;
$driver = getenv('PDODB_DRIVER') ?: 'mysql';
$config = getExampleConfig();
// For SQLite, use a temporary file instead of :memory: for read/write splitting
if ($driver === 'sqlite') {
$config['path'] = sys_get_temp_dir() . '/pdodb_rw_test_' . uniqid() . '.db';
}
echo "=== Read/Write Splitting - Load Balancers ===\n\n";
// ========================================
// 1. Round-Robin Load Balancer
// ========================================
echo "1. Round-Robin Load Balancer\n";
echo " Distributes load evenly in circular order\n\n";
$db1 = new PdoDb($driver, $config);
$db1->enableReadWriteSplitting(new RoundRobinLoadBalancer());
$writeConfig = $config;
$writeConfig['driver'] = $driver;
$writeConfig['type'] = 'write';
$db1->addConnection('write', $writeConfig);
for ($i = 1; $i <= 3; $i++) {
$readConfig = $config;
$readConfig['driver'] = $driver;
$readConfig['type'] = 'read';
$db1->addConnection("read-$i", $readConfig);
}
// Create test table
$db1->rawQuery('DROP TABLE IF EXISTS lb_test');
if ($driver === 'sqlite') {
$db1->rawQuery('CREATE TABLE lb_test (id INTEGER PRIMARY KEY, name TEXT)');
} elseif ($driver === 'pgsql') {
$db1->rawQuery('CREATE TABLE lb_test (id SERIAL PRIMARY KEY, name VARCHAR(255))');
} else {
$db1->rawQuery('CREATE TABLE lb_test (id INT PRIMARY KEY, name VARCHAR(255))');
}
$db1->rawQuery("INSERT INTO lb_test (id, name) VALUES (1, 'Test')");
echo " Load balancer type: " . get_class($db1->getConnectionRouter()->getLoadBalancer()) . "\n";
echo " Read replicas: " . count($db1->getConnectionRouter()->getReadConnections()) . "\n";
// Simulate multiple reads - will distribute across replicas in order
for ($i = 1; $i <= 3; $i++) {
$db1->find()->from('lb_test')->where('id', 1)->getOne();
echo " ✓ Read request $i completed\n";
}
echo "\n";
// ========================================
// 2. Random Load Balancer
// ========================================
echo "2. Random Load Balancer\n";
echo " Randomly selects a replica for each request\n\n";
$db2 = new PdoDb($driver, $config);
$db2->enableReadWriteSplitting(new RandomLoadBalancer());
$writeConfig = $config;
$writeConfig['driver'] = $driver;
$writeConfig['type'] = 'write';
$db2->addConnection('write', $writeConfig);
for ($i = 1; $i <= 3; $i++) {
$readConfig = $config;
$readConfig['driver'] = $driver;
$readConfig['type'] = 'read';
$db2->addConnection("read-$i", $readConfig);
}
echo " Load balancer type: " . get_class($db2->getConnectionRouter()->getLoadBalancer()) . "\n";
echo " Read replicas: " . count($db2->getConnectionRouter()->getReadConnections()) . "\n";
// Simulate multiple reads - will distribute randomly
for ($i = 1; $i <= 3; $i++) {
$db2->find()->from('lb_test')->where('id', 1)->getOne();
echo " ✓ Read request $i completed\n";
}
echo "\n";
// ========================================
// 3. Weighted Load Balancer
// ========================================
echo "3. Weighted Load Balancer\n";
echo " Distributes load based on replica weights\n\n";
$weightedBalancer = new WeightedLoadBalancer();
$weightedBalancer->setWeights([
'read-1' => 3, // Gets 3x more traffic
'read-2' => 2, // Gets 2x more traffic
'read-3' => 1, // Gets 1x traffic (baseline)
]);
$db3 = new PdoDb($driver, $config);
$db3->enableReadWriteSplitting($weightedBalancer);
$writeConfig = $config;
$writeConfig['driver'] = $driver;
$writeConfig['type'] = 'write';
$db3->addConnection('write', $writeConfig);
for ($i = 1; $i <= 3; $i++) {
$readConfig = $config;
$readConfig['driver'] = $driver;
$readConfig['type'] = 'read';
$db3->addConnection("read-$i", $readConfig);
}
echo " Load balancer type: " . get_class($db3->getConnectionRouter()->getLoadBalancer()) . "\n";
echo " Read replicas: " . count($db3->getConnectionRouter()->getReadConnections()) . "\n";
echo " Weights:\n";
echo " read-1: 3 (50% of traffic)\n";
echo " read-2: 2 (33% of traffic)\n";
echo " read-3: 1 (17% of traffic)\n\n";
// Simulate multiple reads to demonstrate weighted distribution
for ($i = 1; $i <= 6; $i++) {
$db3->find()->from('lb_test')->where('id', 1)->getOne();
echo " ✓ Read request $i completed\n";
}
echo "\n";
// ========================================
// 4. Health Checks and Failover
// ========================================
echo "4. Health Checks and Failover\n";
echo " Marking replicas as failed/healthy\n\n";
$balancer = new RoundRobinLoadBalancer();
echo " Marking read-2 as failed...\n";
$balancer->markFailed('read-2');
echo " ✓ read-2 marked as failed (will be skipped)\n\n";
echo " Marking read-2 as healthy...\n";
$balancer->markHealthy('read-2');
echo " ✓ read-2 marked as healthy (will be used again)\n\n";
echo " Resetting all connection states...\n";
$balancer->reset();
echo " ✓ All connections reset\n\n";
// ========================================
// 5. Switching Load Balancers
// ========================================
echo "5. Switching Load Balancers at Runtime\n\n";
$db4 = new PdoDb($driver, $config);
$db4->enableReadWriteSplitting(new RoundRobinLoadBalancer());
$writeConfig = $config;
$writeConfig['driver'] = $driver;
$writeConfig['type'] = 'write';
$db4->addConnection('write', $writeConfig);
$readConfig = $config;
$readConfig['driver'] = $driver;
$readConfig['type'] = 'read';
$db4->addConnection('read-1', $readConfig);
echo " Initial: " . get_class($db4->getConnectionRouter()->getLoadBalancer()) . "\n";
// Switch to RandomLoadBalancer
$db4->getConnectionRouter()->setLoadBalancer(new RandomLoadBalancer());
echo " Switched to: " . get_class($db4->getConnectionRouter()->getLoadBalancer()) . "\n\n";
// ========================================
// 6. Cleanup
// ========================================
echo "6. Cleanup\n";
$db1->rawQuery('DROP TABLE IF EXISTS lb_test');
echo "✓ Test table dropped\n";
// Clean up SQLite temp file
if ($driver === 'sqlite' && isset($config['path']) && file_exists($config['path'])) {
unlink($config['path']);
echo "✓ Temporary SQLite file removed\n";
}
echo "\n=== Example completed successfully ===\n";