这里使用本机模拟负载均衡
nginx 配置如下 [这里使用本地2个端口来模拟两台机器]
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 两个服务,我们用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();
启动两个服务
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 你就会发现9501和9502进行切换
➜ ~ 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
网友评论