nginx负载均衡 页面缓存

nginx的upstream目前支持4种方式的分配

1、轮询(默认)

每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。

2、weight 
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。 
例如: 
upstream bakend { 
server 192.168.0.14 weight=10; 
server 192.168.0.15 weight=10; 
}

2、ip_hash 
每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。 
例如: 
upstream bakend { 
ip_hash; 
server 192.168.0.14:88; 
server 192.168.0.15:80; 
}

3、fair(第三方) 
按后端服务器的响应时间来分配请求,响应时间短的优先分配。 
upstream backend { 
server server1; 
server server2; 
fair; 
}

4、url_hash(第三方)

按访问url的hash结果来分配请求,使每个url定向到同一个后端服务器,后端服务器为缓存时比较有效。

例:在upstream中加入hash语句,server语句中不能写入weight等其他的参数,hash_method是使用的hash算法

upstream backend { 
server squid1:3128; 
server squid2:3128; 
hash $request_uri; 
hash_method crc32; 
}

tips:

upstream bakend{#定义负载均衡设备的Ip及设备状态 
ip_hash; 
server 127.0.0.1:9090 down; 
server 127.0.0.1:8080 weight=2; 
server 127.0.0.1:6060; 
server 127.0.0.1:7070 backup; 

在需要使用负载均衡的server中增加 
proxy_pass ;

每个设备的状态设置为: 
1.down 表示单前的server暂时不参与负载 
2.weight 默认为1.weight越大,负载的权重就越大。 
3.max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误 
4.fail_timeout:max_fails次失败后,暂停的时间。 
5.backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

nginx支持同时设置多组的负载均衡,用来给不用的server来使用。

client_body_in_file_only 设置为On 可以讲client post过来的数据记录到文件中用来做debug 
client_body_temp_path 设置记录文件的目录 可以设置最多3层目录

location 对URL进行匹配.可以进行重定向或者进行新的代理 负载均衡

 

 

如何配置proxy_cache模块

在nginx.conf文件中添加如下代码:

http{  
    ......  
    proxy_cache_path/data/nginx/tmp-test levels=1:2 keys_zone=tmp-test:100m inactive=7d max_size=1000g;  
}
 
代码说明:

proxy_cache_path 缓存文件路径

levels 设置缓存文件目录层次;levels=1:2 表示两级目录

keys_zone 设置缓存名字和共享内存大小

inactive 在指定时间内没人访问则被删除

max_size 最大缓存空间,如果缓存空间满,默认覆盖掉缓存时间最长的资源。
 

当配置好之后,重启nginx,如果不报错,则配置的proxy_cache会生效

 

查看  proxy_cache_path /data/nginx/目录,
会发现生成了tmp-test文件夹。
 

如何使用proxy_cache

在你对应的nginx vhost server配置文件中添加如下代码:
location /tmp-test/ {  
  proxy_cache tmp-test;  
  proxy_cache_valid  200 206 304 301 302 10d;  
  proxy_cache_key $uri;  
  proxy_set_header Host $host:$server_port;  
  proxy_set_header X-Real-IP $remote_addr;  
  proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;  
  proxy_passhttp://127.0.0.1:8081/media_store.php/tmp-test/;  
}
配置项介绍:
Proxy_cache tmp-test 使用名为tmp-test的对应缓存配置

proxy_cache_valid  200 206 304 301 302 10d; 对httpcode为200…的缓存10天

proxy_cache_key $uri  定义缓存唯一key,通过唯一key来进行hash存取

proxy_set_header  自定义http header头,用于发送给后端真实服务器。

proxy_pass  指代理后转发的路径,注意是否需要最后的/
 
到这里,最基本的proxy_cache功能就配置成功了。当uri成功匹配到该location,则proxy_cache就会生效。

 

posted on 2017-12-13 11:29  小V_chen  阅读(295)  评论(0编辑  收藏  举报

导航