动静分离技术

一、HAproxy 动静分离

1、概念:

HAproxy 动静分离技术是一种用于优化 Web 服务器性能和提高用户体验的策略,它通过将动态内容和静态内容分别路由到不同的后端服务器来实现,减轻服务器负载,提高网站的响应速度。

动态内容包括由服务器动态生成的网页内容,如数据库查询结果、用户登录状态等;

静态内容包括不变的文件,如图像、CSS、视频文件等。

2、示例:

(1) 环境:

HAproxy:192.168.198.131

web1:192.168.198.132

web2:192.168.198.133

PHP1:192.168.198.129

PHP2:192.168.198.130

动静分离技术_第1张图片

(2) web 配置:

yum install -y httpd

echo web111 > /var/www/html/index.html

echo web222 > /var/www/html/index.html

systemctl restart httpd

(3) php 配置:

yum install -y httpd php

vim /var/www/html/index.php

phpinfo();

?>

systemctl restart httpd

(4) 配置 haproxy:

vim /etc/haproxy/haproxy.cfg

global
  log 127.0.0.1 local3 info
  maxconn 4096
  user bean
  group bean
  daemon 
  nbproc 1 
  pidfile /run/haproxy.pid

defaults 
  log global 
  mode http 
  maxconn 2048 
  retries 3 
  option redispatch 
  timeout connect 5000 
  timeout client 50000 
  timeout server 50000 
  option abortonclose 

  stats uri /admin?stats 
  stats realm Private lands 
  stats auth admin:123 
  stats hide-version 


frontend http-in 
  bind 0.0.0.0:80 
  mode http 
  log global 
  option httplog 
  option httpclose 
  acl php url_reg -i \.php$ 
  acl html url_reg -i \.html$ 
   use_backend php-server if php 
   use_backend html-server if html 
  default_backend html-server

backend php-server 
  mode http 
  balance roundrobin 
  option httpchk GET /index.php 
  cookie SERVERID insert indirect nocache 
  server php-A 192.168.198.129:80 weight 1 cookie 1 check inter 2000 rise 2 fall 5 
  server php-B 192.168.198.130:80 weight 1 cookie 2 check inter 2000 rise 2 fall 5

backend html-server 
  mode http 
  balance roundrobin 
  option httpchk GET /index.html 
  cookie SERVERID insert indirect nocache 
  server html-A 192.168.198.132:80 weight 1 cookie 3 check inter 2000 rise 2 fall 5 
  server html-B 192.168.198.133:80 weight 1 cookie 4 check inter 2000 rise 2 fall 5

动静分离技术_第2张图片

定义两个 ACL,分别匹配 URL 以 .php 和 .html 为结尾的请求 ;.php 请求交给 php-server 后端服务器,.html 请求交给 html-server 后端服务器。

如果请求的 URL 不匹配任何一个 ACL,将使用 html-server 的后端服务器来处理这些请求。

动静分离技术_第3张图片

php-server 与 html-server 的配置信息。

(5) 测试效果:

启动 haproxy:systemctl restart haproxy

动静分离技术_第4张图片

动静分离技术_第5张图片

登录 haproxy 统计页面:

动静分离技术_第6张图片

二、nginx 动静分离示例:

1、环境:

nginx:192.168.198.128

web1:192.168.198.132

web2:192.168.198.133

PHP1:192.168.198.129

PHP2:192.168.198.130

配置域名解析:

动静分离技术_第7张图片

2、nginx 配置:

vim /etc/nginx/nginx.conf

动静分离技术_第8张图片

● upstream:定义了 html 和 php 两个负载均衡组,包括后端的服务器以及监听的端口号;

● location /:用于处理根 URL 路径(/)的请求,它使用 proxy_pass 指令将请求代理给 html 负载均衡组,再分发给 web1 和 web2 服务器。

● location ~ \.php$:使用正则表达式匹配以 .php 结尾的 URL 路径,使用proxy_pass 指令将请求代理给 php 负载均衡组,再分发给 php1 和 php2 服务器。

你可能感兴趣的:(负载均衡,haproxy,nginx,web,php)