记录一下,一个简单可用的Nginx负载均衡配置文件。
本地测试是可以用的。
本地环境:
开启了三个本地服务:
127.0.0.1:8082;
127.0.0.1:8083;
127.0.0.1:8084;
每个服务器,提供两个测试接口:
以127.0.0.1:8082服务为例:
http://localhost:8082/ # index
http://localhost:8082/user?userId=12345 # userId
HomeController和UserController
@Slf4j
@RestController
public class HomeController {
@Value("${server.port}")
private String port;
@GetMapping("/")
public String index() {
log.info("HomeController#index port:{}", port);
return "index:" + port;
}
}
UserController
@RestController
@RequestMapping("user")
public class UserController {
@Value("${server.port}")
private String port;
@GetMapping
public String get(@RequestParam Long userId) {
return "port:" + port + ",userId:" + String.valueOf(userId);
}
}
用于测试的URL
http://localhost/
http://localhost/user?userId=12345
nginx配置文件如下:
upstream 是关键
user www www; ## Default: nobody
worker_processes 1; ## Default: 1
error_log /Users/lucas/logs/error.log;
pid /Users/lucas/logs/nginx.pid;
worker_rlimit_nofile 8192;
events {
worker_connections 1024; ## Default: 1024
}
http {
include /Users/lucas/Desktop/local-mime.types;
#include /etc/nginx/proxy.conf;
#include /etc/nginx/fastcgi.conf;
index index.html index.htm index.php;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $status '
'"$request" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /Users/lucas/logs/access.log main;
sendfile on;
tcp_nopush on;
server_names_hash_bucket_size 128; # this seems to be required for some vhosts
server { # test
listen 80;
server_name test1.com test2.com;
access_log /Users/lucas/logs/test1.access.log main;
root html;
location ~ \.php$ {
fastcgi_pass 127.0.0.1:1025;
}
}
upstream spacex-fox-qiong {
server 127.0.0.1:8082;
server 127.0.0.1:8083;
server 127.0.0.1:8084;
}
server { # simple reverse-proxy
listen 80;
server_name localhost;
access_log /Users/lucas/logs/localhost.access.log main;
# serve static files
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/virtual/spacex.server.com/htdocs;
expires 30d;
}
# pass requests for dynamic content to rails/turbogears/zope, et al
location / {
proxy_pass http://spacex-fox-qiong;
}
}
upstream spacex-server.com {
server 127.0.0.3:8000 weight=5;
server 127.0.0.3:8001 weight=5;
server 192.168.0.1:8000;
server 192.168.0.1:8001;
}
server { # simple load balancing
listen 80;
server_name big.server.com;
access_log /Users/lucas/logs/spacex.server.access.log main;
location / {
proxy_pass http://spacex-server.com;
}
}
}
(完)