使用Idea快速创建一个Spring Boot Web应用程序,作为被Nginx反向代理的后端服务集群,
核心代码如下
分别在8881、8882、8883端口启动这个Java Web程序
这里就不放入后台执行了,用Xshell打开三个终端吧
配置nginx的配置文件
$ vim $NGINX_HOME/conf/nginx.confworker_processes auto;events { use epoll; worker_connections 65535;}http { upstream aidan.org{ server 127.0.0.1:8881; server 127.0.0.1:8882; server 127.0.0.1:8883; } server { listen 80; server_name aidan.org; location / { proxy_pass http://aidan.org; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }}重新加载nginx配置
$ nginx -s reload配置host文件
$ vim /etc/hosts127.0.0.1 aidan.org使用curl测试nginx基于轮询的负载均衡
[root@localhost ~]# curl aidan.orghello nginx,I'm 8881 Server.nginx host is aidan.org,your realIp is 127.0.0.1[root@localhost ~]# curl aidan.orghello nginx,I'm 8882 Server.nginx host is aidan.org,your realIp is 127.0.0.1[root@localhost ~]# curl aidan.orghello nginx,I'm 8883 Server.nginx host is aidan.org,your realIp is 127.0.0.1发现端口号的变化了没?
使用浏览器测试一下nginx转发客户端的真实IP(192.168.1.162)
1 nginx缺省配置就是轮询策略
2 nginx负载均衡支持http和https协议,只需要修改proxy_pass后协议即可
3 nginx支持FastCGI、uwsgi、SCGI、memcached的负载均衡:只需将proxy_pass改为fastcgi_pass、uwsgi_pass、scgi_pass、memchached_pass即可。
nginx.conf文件中轮询负载均衡的配置是重点
另外配置中还演示了nginx添加请求头的方式传递客户端的真实IP给后端服务器实例
nginx配置文件的风格: