這里使用本機(jī)模擬負(fù)載均衡
nginx 配置如下 [這里使用本地2個(gè)端口來模擬兩臺(tái)機(jī)器]
upstream web001 {
server 127.0.0.1:9501;
server 127.0.0.1:9502;
}
server {
listen 80;
server_name upstream.localhost.com;
location / {
proxy_pass http://web001;
}
}
9501,9502 兩個(gè)服務(wù)挎狸,我們用swoole來模擬振湾,代碼分別為
http1.php
<?php
$http = new swoole_http_server("127.0.0.1", 9501);
$http->on("start", function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9501\n";
});
$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World this is 9501 \n");
});
$http->start();
http2.php
<?php
$http = new swoole_http_server("127.0.0.1", 9502);
$http->on("start", function ($server) {
echo "Swoole http server is started at http://127.0.0.1:9502\n";
});
$http->on("request", function ($request, $response) {
$response->header("Content-Type", "text/plain");
$response->end("Hello World this is 9502 \n");
});
$http->start();
啟動(dòng)兩個(gè)服務(wù)
php http1.php
Swoole http server is started at http://127.0.0.1:9502
php http2.php
Swoole http server is started at http://127.0.0.1:9502
curl 請求 upstream.localhost.com 你就會(huì)發(fā)現(xiàn)9501和9502進(jìn)行切換
? ~ curl http://upstream.localhost.com
Hello World this is 9502
? ~ curl http://upstream.localhost.com
Hello World this is 9501
? ~ curl http://upstream.localhost.com
Hello World this is 9502
? ~ curl http://upstream.localhost.com
Hello World this is 9501