目的是将 http://127.0.0.1/demo 负载均衡转发到 http://127.0.0.1/demo1和http://127.0.0.1/demo2
第一步,开启项目模块:
LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule lbmethod_byrequests_module modules/mod_lbmethod_byrequests.so LoadModule slotmem_shm_module modules/mod_slotmem_shm.so
第二步,负载均衡代理配置,写在httpd.conf文件下面:
可配置一个或者多个负载代理,democluster 为该代理的命名,后面需要通过引用该名字调用负载均衡转发ProxyRequests Off <Proxy balancer://democluster> BalancerMember http://127.0.0.1:8080/demo1 BalancerMember http://127.0.0.1:8080/demo2 </Proxy>
开启负载均衡管理界面 http://127.0.0.1/balancer-manager,生产环境慎重开启:
<Location /balancer-manager> SetHandler balancer-manager Require all granted </Location>
(Apache2.4:Require all granted,Apache2.2:Allow from all)
第三步,应用负载均衡,在虚拟服务器中使用,也可以直接根配置(httpd.conf)中使用:
<VirtualHost 127.0.0.1:80> ServerAdmin [email protected] ServerName 127.0.0.1 ProxyRequests Off ProxyPreserveHost On <Proxy *> Require all granted </Proxy> ProxyPass /demo balancer://democluster ProxyPassReverse /demo balancer://democluster ErrorLog "logs/test.localhost-error_log" CustomLog "logs/test.localhost-access_log" common </VirtualHost>
其他,也可以将第二步中的负载均衡代理配置,直接配置到虚拟主机中,如下:
<VirtualHost 127.0.0.1:80> ServerAdmin [email protected] ServerName 127.0.0.1 ProxyRequests Off ProxyPreserveHost On <Proxy balancer://democluster> BalancerMember http://127.0.0.1:8080/demo1 BalancerMember http://127.0.0.1:8080/demo2 </Proxy> ProxyPass /demo balancer://democluster ProxyPassReverse /demo balancer://democluster ErrorLog "logs/test.localhost-error_log" CustomLog "logs/test.localhost-access_log" common </VirtualHost>
-------------------------------------------------------------------------------------
相关配置和策略说明
负载权重设置,按照比例设置分发权重,在分发链接后面加上loadfactor:
<Proxy balancer://democluster> BalancerMember http://127.0.0.1:8080/demo1 loadfactor=3 BalancerMember http://127.0.0.1:8080/demo2 loadfactor=7 </Proxy>
分发策略设置,通过设置lbmethod设置分发策略:
lbmethod:表示负载载均衡策略。
lbmethod=byrequests :按照请求次数均衡(默认)
lbmethod=bytraffic: 按照流量均衡
lbmethod=bybusyness :按照繁忙程度均衡(总是分配给活跃请求数最少的服务器)
<Proxy balancer://democluster> BalancerMember http://127.0.0.1:8080/demo1 loadfactor=3 BalancerMember http://127.0.0.1:8080/demo2 loadfactor=7 ProxySet lbmethod=byrequests </Proxy>
ProxyPass /demo balancer://democluster lbmethod=bytraffic
<Proxy balancer://democluster> BalancerMember http://127.0.0.1:8080/demo1 BalancerMember http://127.0.0.1:8080/demo2 status=+H </Proxy>