1.设置在何种情况下nginx不从cache取数据

Syntax:proxy_cache_bypass string ...;

Default:

Context:http, server, location

Defines conditions under which the response will not be taken from a cache. If at least one value of the string parameters is not empty and is not equal to “0” then the response will not be taken from the cache:


proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;

proxy_cache_bypass $http_pragma    $http_authorization;


session绑定,讲同一客户端的请求发往同一服务器,有3种方法,cookie;route;learn.

Syntax:sticky cookie name [expires=time] [domain=domain] [httponly] [secure] [path=path];

sticky route $variable ...;

sticky learn create=$variable lookup=$variable zone=name:size [timeout=time];

Default:

Context:upstream

This directive appeared in version 1.5.7.

Enables session affinity, which causes requests from the same client to be passed to the same server in a group of servers. Three methods are available:


2.cookie通过浏览器识别不同用户,访问判定使用哪个服务器

    When the cookie method is used, information about the designated server is passed in an HTTP cookie generated by nginx:

    

    upstream backend {

        server backend1.example.com;

        server backend2.example.com;

    

        sticky cookie srv_id expires=1h domain=.example.com path=/;

    }

    A request that comes from a client not yet bound to a particular server is passed to the server selected by the configured balancing method. Further requests with this cookie will be passed to the designated server. If the designated server cannot process a request, the new server is selected as if the client has not been bound yet.

    

    The first parameter sets the name of the cookie to be set or inspected. Additional parameters may be as follows:

    

    expires=time

    Sets the time for which a browser should keep the cookie. The special value max will cause the cookie to expire on “31 Dec 2037 23:55:55 GMT”. If the parameter is not specified, it will cause the cookie to expire at the end of a browser session.

    domain=domain

    Defines the domain for which the cookie is set.

    httponly

    Adds the HttpOnly attribute to the cookie (1.7.11).

    secure

    Adds the Secure attribute to the cookie (1.7.11).

    path=path

    Defines the path for which the cookie is set.

    If any parameters are omitted, the corresponding cookie fields are not set.


3.调度方法,最少连接,加权的最少连接

Syntax:least_conn;

Default:

Context:upstream

This directive appeared in versions 1.3.1 and 1.2.2.

Specifies that a group should use a load balancing method where a request is passed to the server with the least number of active connections, taking into account weights of servers. If there are several such servers, they are tried in turn using a weighted round-robin balancing method.


4.保持长连接数,memcache,fastcgi,http,词个有特殊用法,具体见http://nginx.org/en/docs/

建议:当后面是http服务器,不建议使用。

Syntax:keepalive connections;

Default:

Context:upstream

This directive appeared in version 1.1.4.

Activates the cache for connections to upstream servers.


5.对于组内所有主机健康状态检测,对与realsever返回过来的数据做健康检测。

注意:建议关闭访问日志,不然5s发日志无意义。

Syntax:health_check [parameters];

Default:

Context:location

Enables periodic health checks of the servers in a group referenced in the surrounding location.


The following optional parameters are supported:


interval=time

sets the interval between two consecutive health checks, by default, 5 seconds;

fails=number

sets the number of consecutive failed health checks of a particular server after which this server will be considered unhealthy, by default, 1;

passes=number

sets the number of consecutive passed health checks of a particular server after which the server will be considered healthy, by default, 1;

uri=uri

defines the URI used in health check requests, by default, “/”;

match=name

specifies the match block configuring the tests that a response should pass in order for a health check to pass; by default, the response should have status code 2xx or 3xx.

For example,


location / {

    proxy_pass http://backend;

    health_check;

}


6.设置nginx与客户端之间;自定义请求首部

wKioL1Y_AEXR7XDpAAAG706lH3A199.jpg

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

  1 server {

  2     listen       80;

  3     server_name  localhost;

  4     add_header x-Via    $server_addr;    ##返回客户端是后端还是代理端IP

[root@node1 ~]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 ~]# service nginx reload

重新载入 nginx:                                           [确定]

wKioL1Y_Ab-yPcKTAAHtMNTVDrk679.jpg


客户端与nginx之间,使用缓存功能,告诉客户端是否命中缓存。注意,必须开启缓存。

wKioL1Y_AEXR7XDpAAAG706lH3A199.jpg

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

 14     location /forum/ {

 15         proxy_cache_valid 200 1d;

 16         proxy_cache_valid 301 302 10m;

 17         proxy_cache_valid any 1m;

 18         proxy_cache_use_stale error timeout http_500 http_502 htt    p_503 http_504;

 19         proxy_cache mycache;

 20         proxy_pass http://upservers/;

 21         proxy_set_header Host $host;

 22         proxy_set_header X-Real-IP $remote_addr;

 23         add_header X-Cache $upstream_cache_status;  

 24    }

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

[root@node1 ~]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 ~]# service nginx reload

重新载入 nginx:                                           [确定]

wKiom1Y_Bgzygf4qAAIhE03iVGM125.jpg

-----------------------------------------------------------------


7.$upstream_cache_status 缓存状态

keeps the status of accessing a response cache (0.8.3). The status can be either “MISS”, “BYPASS”, “EXPIRED”, “STALE”, “UPDATING”, “REVALIDATED”, or “HIT”.


8.指定名称

$upstream_cookie_name

cookie with the specified name sent by the upstream server in the “Set-Cookie” response header field (1.7.1). Only the cookies from the response of the last server are saved.


9.uptream给nginx的响应码

$upstream_status

keeps status code of the response obtained from the upstream server. Status codes of several responses are separated by commas and colons like addresses in the $upstream_addr variable.

----------------------------------------------------------------------------------


LNMP+fastcgi(本机)如果分离式请修改IP

本机安装fastcgi,响应php

[root@node1 ~]# yum install php-fpm -y

[root@node1 ~]# rpm -ql php-fpm

/etc/logrotate.d/php-fpm

/etc/php-fpm.conf

/etc/php-fpm.d

/etc/php-fpm.d/www.conf

/etc/rc.d/init.d/php-fpm

/etc/sysconfig/php-fpm

/usr/sbin/php-fpm

/usr/share/doc/php-fpm-5.3.3

/usr/share/doc/php-fpm-5.3.3/LICENSE

/usr/share/doc/php-fpm-5.3.3/php-fpm.conf.default

/usr/share/fpm/status.html

/usr/share/man/man8/php-fpm.8.gz

/var/log/php-fpm

/var/run/php-fpm

[root@node1 ~]# vim /etc/php-fpm.d/www.conf 

[root@node1 ~]# service php-fpm start

正在启动 php-fpm:                                         [确定]

[root@node1 ~]# ss -tanlp | grep 9000

LISTEN     0      128               127.0.0.1:9000                     *:*      users:(("php-fpm",5916,7),("php-fpm",5917,0),("php-fpm",5918,0),("php-fpm",5919,0),("php-fpm",5920,0),("php-fpm",5921,0))


[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

 55     location ~ \.php$ {

 56         root           html;

 57         fastcgi_pass   127.0.0.1:9000;

 58         fastcgi_index  index.php;

 59         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

 60         include        fastcgi_params;

 61     }

[root@node1 ~]# vim /etc/nginx/fastcgi_params

[root@node1 ~]# cd /usr/share/nginx/html/

[root@node1 html]# ls

50x.html  index.html

[root@node1 html]# mv index.html nginx.html

[root@node1 html]# ls

50x.html  nginx.html

[root@node1 html]# vim index.php

  1 <?php

  2 phpinfo();

  3 ?>

[root@node1 html]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 html]# service nginx reload

重新载入 nginx:                                           [确定]

[root@node1 html]# vim /etc/nginx/fastcgi_params 

  fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;

    fastcgi_param  SERVER_SOFTWARE    nginx;

    fastcgi_param  QUERY_STRING       $query_string;

    fastcgi_param  REQUEST_METHOD     $request_method;

    fastcgi_param  CONTENT_TYPE       $content_type;

    fastcgi_param  CONTENT_LENGTH     $content_length;

    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

    fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

    fastcgi_param  REQUEST_URI        $request_uri;

    fastcgi_param  DOCUMENT_URI       $document_uri;

    fastcgi_param  DOCUMENT_ROOT      $document_root;

    fastcgi_param  SERVER_PROTOCOL    $server_protocol;

    fastcgi_param  REMOTE_ADDR        $remote_addr;

    fastcgi_param  REMOTE_PORT        $remote_port;

    fastcgi_param  SERVER_ADDR        $server_addr;

    fastcgi_param  SERVER_PORT        $server_port;

    fastcgi_param  SERVER_NAME        $server_name;

[root@node1 html]# service nginx reload

重新载入 nginx:  

wKioL1Y_MpeAe5LaAAQy-t_PRHo674.jpg

[root@node1 html]# yum install php-mysql -y

[root@node1 html]# rpm -ql php-fpm

/etc/logrotate.d/php-fpm

/etc/php-fpm.conf

/etc/php-fpm.d

/etc/php-fpm.d/www.conf

/etc/rc.d/init.d/php-fpm

/etc/sysconfig/php-fpm

/usr/sbin/php-fpm

/usr/share/doc/php-fpm-5.3.3

/usr/share/doc/php-fpm-5.3.3/LICENSE

/usr/share/doc/php-fpm-5.3.3/php-fpm.conf.default

/usr/share/fpm/status.html

/usr/share/man/man8/php-fpm.8.gz

/var/log/php-fpm

/var/run/php-fpm

[root@node1 html]# rpm -ql php-mysql

/etc/php.d/mysql.ini

/etc/php.d/mysqli.ini

/etc/php.d/pdo_mysql.ini

/usr/lib64/php/modules/mysql.so

/usr/lib64/php/modules/mysqli.so

/usr/lib64/php/modules/pdo_mysql.so

[root@node1 html]# service php-fpm reload

重新载入 php-fpm:[19-Oct-2015 22:49:03] NOTICE: configuration file /etc/php-fpm.conf test is successful                  [确定]

wKiom1Y_NFnA1Ea7AAN5lkarsRc993.jpg

[root@node1 html]# yum install mysql-server -y

[root@node1 html]# service mysqld start

[root@node1 html]# ss -tanl 

State      Recv-Q Send-Q   Local Address:Port     Peer Address:Port 

LISTEN     0      128          127.0.0.1:9000                *:*     

LISTEN     0      50                   *:3306                *:*     

LISTEN     0      128                  *:80                  *:*     

LISTEN     0      128                 :::22                 :::*     

LISTEN     0      128                  *:22                  *:*     

LISTEN     0      128          127.0.0.1:631                 *:*     

LISTEN     0      128                ::1:631                :::*     

LISTEN     0      100                ::1:25                 :::*     

LISTEN     0      100          127.0.0.1:25                  *:*     

LISTEN     0      128          127.0.0.1:6010                *:*     

LISTEN     0      128                ::1:6010               :::*     

LISTEN     0      128          127.0.0.1:6011                *:*     

LISTEN     0      128                ::1:6011               :::*  


[root@node1 html]# vim /usr/share/nginx/html/index.php 

<?php

  $conn = mysql_connect('127.0.0.1','root','');

 if ($conn)

        echo succ;

  else

          echo fail;

          mysql_close();

  ?>

wKioL1Y_NkLjhqRUAAB83R9KZv4794.jpg

[root@node1 html]# service mysqld stop

停止 mysqld:                                              [确定]

wKioL1Y_NpaDsKkJAACDYfRd5MQ176.jpg

-----------------------------------------------------------------------------------------

实现 LNAMP

wKioL1Y_AEXR7XDpAAAG706lH3A199.jpg

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

  9     location / {

 10         root   /var/www/html;

 11         index index.php index.html index.htm;

 12         proxy_pass http://upservers/;

 13     }

 56     #location ~ \.php$ {

 57      #   root   /usr/share/nginx/html;

 58       #  fastcgi_pass   127.0.0.1:9000;

 59        # fastcgi_index  index.php;

 60        # fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_n    ame;

 61        # include        fastcgi_params;

 62    # }

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 ~]# service nginx reload

重新载入 nginx:                                           [确定]


wKioL1Y_XHHBqZKNAAAHR6o7Z_s236.jpg

[root@node3 ~]# vim /var/www/html/index.php

  1  <?php

  2    $conn = mysql_connect('127.0.0.1','root','');

  3    if ($conn)

  4            echo succ;

  5    else

  6            echo fail;

  7            mysql_close();

  8    ?>

[root@node3 ~]# yum install mysql mysql-server -y

[root@node3 ~]# yum install php php-fpm php-mysql -y

[root@node3 ~]# vim /etc/httpd/conf/httpd.conf

 402 DirectoryIndex index.php index.html index.html.var

[root@node3 ~]# servie httpd restart

[root@node3 ~]# service mysqld restart

[root@node3 ~]# service php-fpm restart

wKioL1Y_XU_RGmGBAANYOFOZa-E762.jpg


fastcgi的常用配置:

1.配置缓存路径,缓存名

Syntax:fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

Default:

Context:http

Sets the path and other parameters of a cache. Cache data are stored in files. Both the key and file name in a cache are a result of applying the MD5 function to the proxied URL. The levels parameter defines hierarchy levels of a cache. For example, in the following configuration


fastcgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

file names in a cache will look like this:


/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c


2.调用缓存

Syntax:fastcgi_cache zone | off;

Default:fastcgi_cache off;

Context:http, server, location

Defines a shared memory zone used for caching. The same zone can be used in several places. Parameter value can contain variables (1.7.9). The off parameter disables caching inherited from the previous configuration level.


3.限制上传反向服务器的速率

Syntax:fastcgi_limit_rate rate;

Default:

fastcgi_limit_rate 0;

Context:http, server, location

This directive appeared in version 1.7.7.

Limits the speed of reading the response from the FastCGI server. 



wKioL1Y_AEXR7XDpAAAG706lH3A199.jpg

[root@node1 ~]# vim /etc/nginx/nginx.conf

 24     fastcgi_cache_path /cache/fastcgi levels=1:1 keys_zone=fcgicache:32m inactive=3m max_size=1g;

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

 55     location ~ \.php$ {

 56         fastcgi_cache_valid 200 1d;

 57         fastcgi_cache_valid 301 302 10m;

 58          fastcgi_cache_valid any 1m;

 59         fastcgi_cache_use_stale error timeout invalid_header http_500;

 60         fastcgi_cache   fcgicache;

 61         root   /usr/share/nginx/html;

 62         fastcgi_pass   127.0.0.1:9000;

 63         fastcgi_index  index.php;

 64         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

 65         include        fastcgi_params;

 66         fastcgi_cache_key $request_method://$host$request_uri;

 67         add_header X-Cache $upstream_cache_status;

 68 }

[root@node1 ~]# mkdir /cache/fastcgi

mkdir: 无法创建目录"/cache/fastcgi": 文件已存在

[root@node1 ~]# chown -R nginx.nginx /cache/fastcgi

[root@node1 ~]# vim /usr/share/nginx/html/test.php   

  1 <?php

  2  phpinfo();

  3 ?>

wKioL1Y_fHTgjMVdAAPkTVV_JxI296.jpg


测试缓存

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

location ~ \.php$ {

 56         fastcgi_cache_valid 200 1d; 

 57         fastcgi_cache_valid 301 302 10m;

 58          fastcgi_cache_valid any 1m;  

            fastcgi_cache_use_stale error timeout invalid_header http_ 500;    

 60         fastcgi_cache   off;

 61         root   /usr/share/nginx/html;

 62         fastcgi_pass   127.0.0.1:9000;

 63         fastcgi_index  index.php; 

64         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;     

 65         include        fastcgi_params;

 66         fastcgi_cache_key $request_method://$host$request_uri;

 67         add_header X-Cache $upstream_cache_status;

 68 }

[root@node1 7]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 7]# service nginx reload

重新载入 nginx:                                           [确定]

[root@node1 ~]# ab -n 2000 -c 200 http://192.168.204.130/test.php

This is ApacheBench, Version 2.3 <$Revision: 655654 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Licensed to The Apache Software Foundation, http://www.apache.org/


Benchmarking 192.168.204.130 (be patient)

Completed 200 requests

Completed 400 requests

Completed 600 requests

Completed 800 requests

Completed 1000 requests

Completed 1200 requests

Completed 1400 requests

Completed 1600 requests

Completed 1800 requests

Completed 2000 requests

Finished 2000 requests


Server Software:        nginx/1.8.0

Server Hostname:        192.168.204.130

Server Port:            80


Document Path:          /test.php

Document Length:        45386 bytes


Concurrency Level:      200

Time taken for tests:   4.088 seconds

Complete requests:      2000

Failed requests:        0

Write errors:           0

Total transferred:      91064000 bytes

HTML transferred:       90772000 bytes

Requests per second:    489.26 [#/sec] (mean)

Time per request:       408.780 [ms] (mean)

Time per request:       2.044 [ms] (mean, across all concurrent requests)

Transfer rate:          21754.90 [Kbytes/sec] received


Connection Times (ms)

              min  mean[+/-sd] median   max

Connect:        0   55 242.0      0    3000

Processing:     2  277 139.2    258    1670

Waiting:        0  277 139.1    257    1670

Total:         57  333 278.7    259    3260


Percentage of the requests served within a certain time (ms)

  50%    259

  66%    265

  75%    269

  80%    275

  90%    331

  95%   1135

  98%   1261

  99%   1267

 100%   3260 (longest request)

[root@node1 ~]# service nginx restart

停止 nginx:                                               [确定]

正在启动 nginx:

[root@node1 ~]# ab -n 2000 -c 200 http://192.168.204.130/test.php

This is ApacheBench, Version 2.3 <$Revision: 655654 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Licensed to The Apache Software Foundation, http://www.apache.org/


Benchmarking 192.168.204.130 (be patient)

Completed 200 requests

Completed 400 requests

Completed 600 requests

Completed 800 requests

Completed 1000 requests

Completed 1200 requests

Completed 1400 requests

Completed 1600 requests

Completed 1800 requests

Completed 2000 requests

Finished 2000 requests


Server Software:        nginx/1.8.0

Server Hostname:        192.168.204.130

Server Port:            80


Document Path:          /test.php

Document Length:        45386 bytes


Concurrency Level:      200

Time taken for tests:   0.929 seconds

Complete requests:      2000

Failed requests:        0

Write errors:           0

Total transferred:      91092000 bytes

HTML transferred:       90772000 bytes

Requests per second:    2152.79 [#/sec] (mean)

Time per request:       92.903 [ms] (mean)

Time per request:       0.465 [ms] (mean, across all concurrent requests)

Transfer rate:          95752.70 [Kbytes/sec] received


Connection Times (ms)

              min  mean[+/-sd] median   max

Connect:        0    3   5.4      1      20

Processing:    19   43  16.9     43     612

Waiting:        0   42  17.6     42     612

Total:         35   46  16.6     44     612


Percentage of the requests served within a certain time (ms)

  50%     44

  66%     46

  75%     48

  80%     49

  90%     56

  95%     60

  98%     62

  99%     64

 100%    612 (longest request)

-----------------------------------------------------------------------------------

一个完整配置例(生产环境中使用)


user                              nobody nobody;

worker_processes                  4;

worker_rlimit_nofile              51200;


error_log                         logs/error.log  notice;


pid                               /var/run/nginx.pid;


events {

  use                             epoll;

  worker_connections              51200;

}


http {

  server_tokens                   off   防止错误页面上的服务器信息,泄漏

  include                         mime.types;


  proxy_redirect                off;  重定向

  proxy_set_header              Host $host;

  proxy_set_header              X-Real-IP $remote_addr;

  proxy_set_header              X-Forwarded-For $proxy_add_x_forwarded_for;使用在多级服务器上

  client_max_body_size          20m;   客户端最大的主体部分,跟上传单个文件有关

  client_body_buffer_size       256k;    客户端上传的buffer/client

  proxy_connect_timeout         90;      与后端连接的超时时间

  proxy_send_timeout            90;    后端发送nginx超时

  proxy_read_timeout            90;    后端读取后端响应的超时时间

  proxy_buffer_size             128k;    nginx服务器的bufffer

  proxy_buffers                 4 64k;  代理服务器有4个buffer,每个64K

  proxy_busy_buffers_size       128k;

  proxy_temp_file_write_size    128k;


  default_type                    application/octet-stream;

  charset                         utf-8;

  

  client_body_temp_path           /var/tmp/client_body_temp 1 2;

  proxy_temp_path                 /var/tmp/proxy_temp 1 2;

  fastcgi_temp_path               /var/tmp/fastcgi_temp 1 2;

  uwsgi_temp_path                 /var/tmp/uwsgi_temp 1 2;

  scgi_temp_path                  /var/tmp/scgi_temp 1 2;


  ignore_invalid_headers          on;   忽略不合法的首部

  server_names_hash_max_size      256;    主机通过hash到内存,快速定位后端主机

  server_names_hash_bucket_size   64;       同上

  client_header_buffer_size       8k;      读取客户端的首部buffer

  large_client_header_buffers     4 32k;

  connection_pool_size            256;

  request_pool_size               64k;


  output_buffers                  2 128k;

  postpone_output                 1460;


  client_header_timeout           1m;

  client_body_timeout             3m;

  send_timeout                    3m;


  log_format main             '$server_addr $remote_addr [$time_local] $msec+$connection '

        '"$request" $status $connection $request_time $body_bytes_sent "$http_referer" '

                      '"$http_user_agent" "$http_x_forwarded_for"';


  open_log_file_cache          max=1000 inactive=20s min_uses=1 valid=1m;


  access_log                    logs/access.log      main;

  log_not_found                   on;


  sendfile                       on;

  tcp_nodelay                     on;

  tcp_nopush                     off;


  reset_timedout_connection       on;

  keepalive_timeout               10 5;

  keepalive_requests              100;


  gzip                        on;

  gzip_http_version               1.1;

  gzip_vary                       on;

  gzip_proxied                    any;

  gzip_min_length                 1024;

  gzip_comp_level                 6;

  gzip_buffers                    16 8k;

  gzip_proxied                    expired no-cache no-store private auth no_last_modified no_etag;

  gzip_types                      text/plain application/x-javascript text/css application/xml application/json;

  gzip_disable                    "MSIE [1-6]\.(?!.*SV1)";


  upstream tomcat8080 {

    ip_hash;


    server                       172.16.100.103:8080 weight=1 max_fails=2;

    server                       172.16.100.104:8080 weight=1 max_fails=2;

    server                       172.16.100.105:8080 weight=1 max_fails=2;

  }


  server {

    listen                        80;

    server_name                   www.magedu.com;

    # config_apps_begin

    root                         /data/webapps/htdocs;

    access_log                  /var/logs/webapp.access.log     main;

    error_log                   /var/logs/webapp.error.log     notice;


    location / {

    

      location ~* ^.*/favicon.ico$ {   ##图标

        root                     /data/webapps;

        expires                   180d;

        break;

      }

    

      if ( !-f $request_filename ) {

        proxy_pass                http://tomcat8080;

        break;

      }

    }


    error_page                   500 502 503 504  /50x.html;

      location = /50x.html {

      root                        html;

    }

  }


  server {

    listen                        8088;

    server_name                   nginx_status;


      location / {

          access_log                  off;

          deny                        all;

          return                      503;

      }


      location /status {

          stub_status                 on;

          access_log                  off;

          allow                       127.0.0.1;

          allow                       172.16.100.71;

          deny                        all;

      }

  }


}


正向代理

以客户端为中心获取服务端的内容,通过代理服务器的方式获取。有缓存。

反向代理

以服务端为中心,客户端通过访问代理服务器即认为是服务端,其中代理服务器通过转发到服务端响应。有缓存。

nginx反向代理:

客户端发送请求到nginx,要将发送请求全部缓存完,才会转发去后端服务器。属于异步。

后端服务器响应时,发送到nginx,nginx边接受后端发来的响应,便发送至客户端。后端服务器以为响应较快,代理服务器来不及发送完毕,此代理服务器和后端服务器连接会将延长。


内存及磁盘资源分配:

1、client_body_in_file_only on|clean|off

HTTP的包体是否存储在磁盘文件中;非off表示存储,即使包体大小为0也会创建一个磁盘文件;on表示请求结束后包体文件不会被删除,clean表示会被删除;


2、client_body_in_single_buffer on|off;

HTTP的包体是否存储在内存buffer当中;默认为off;


3、cleint_body_buffer_size size;

nginx接收HTTP包体的内存缓冲区大小;


4、client_body_temp_path dir-path [level1 [level2 [level3]]];

HTTP包体存放的临时目录;

client_body_temp_path /var/tmp/client/  1 2


5、client_header_buffer_size size;

正常情况下接收用户请求的http报文header部分时分配的buffer大小;默认为1k;


6、large_client_header_buffers number size; 

存储超大Http请求首部的内存buffer大小及个数;


7、connection_pool_size size;

nginx对于每个建立成功的tcp连接都会预先分配一个内存池,此处即用于设定此内存池的初始大小;默认为256;一般为妥协数据。如果超出之后回向内核扩容,这个又牵涉到系统调用,会影响运行模式转换,影响性能;太大会浪费内存。


8、request_pool_size size;

nginx在处理每个http请求时会预先分配一个内存池,此处即用于设定此内存池的初始大小;默认为4k; 


Nginx反向代理


Nginx通过proxy模块实现反向代理功能。在作为web反向代理服务器时,nginx负责接收客户请求,并能够根据URI、客户端参数或其它的处理逻辑将用户请求调度至上游服务器上(upstream server)。nginx在实现反向代理功能时的最重要指令为proxy_pass,它能够将location定义的某URI代理至指定的上游服务器(组)上。如下面的示例中,location的/uri将被替换为上游服务器上的/newuri。如果是proxy后面没有/,就直接替换http://www.magedu.com:8080/uri


location /uri {

proxy_pass http://www.magedu.com:8080/newuri;

}


不过,这种处理机制中有两个例外。一个是如果location的URI是通过模式匹配定义的,其URI将直接被传递至上游服务器,而不能为其指定转换的另一个URI。例如下面示例中的/bbs将被代理为http://www.magedu.com/bbs。


location ~ ^/bbs {

proxy_pass http://www.magedu.com;

}


第二个例外是,如果在loation中使用的URL重定向,那么nginx将使用重定向后的URI处理请求,而不再考虑上游服务器上定义的URI。如下面所示的例子中,传送给上游服务器的URI为/index.php?page=<match>,而不是/index。


location / {

rewrite /(.*)$ /index.php?page=$1 break;

proxy_pass http://localhost:8080/index;

}


 proxy模块的指令


proxy模块的可用配置指令非常多,它们分别用于定义proxy模块工作时的诸多属性,如连接超时时长、代理时使用http协议版本等。下面对常用的指令做一个简单说明。


proxy_connect_timeout:nginx将一个请求发送至upstream server之前等待的最大时长;

proxy_cookie_domain:将upstream server通过Set-Cookie首部设定的domain属性修改为指定的nginx,domain值,方便与客户端通信。其值可以为一个字符串、正则表达式的模式或一个引用的变量;

proxy_cookie_path: 将upstream server通过Set-Cookie首部设定的path属性修改为指定的值,其值可以为一个字符串、正则表达式的模式或一个引用的变量;

proxy_hide_header:设定发送给客户端的报文中需要隐藏的首部,主要是从后端服务器发来的头部信息;

proxy_pass:指定将请求代理至upstream server的URL路径;

proxy_set_header:将发送至upsream server的报文的某首部进行重写;

proxy_redirect:重写location并刷新从upstream server收到的报文的首部;

proxy_send_timeout:在连接断开之前两次发送至upstream server的写操作的最大间隔时长;

proxy_read_timeout:在连接断开之前两次从接收upstream server接收读操作的最大间隔时长;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;谁转发的


如下面的一个示例:

proxy_redirect off;

proxy_set_header Host $host;

proxy_set_header X-Real-IP $remote_addr;

proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

client_max_body_size 10m;

client_body_buffer_size 128k;

proxy_connect_timeout 30;

proxy_send_timeout 15;

proxy_read_timeout 15;


proxy_set_header X-Real-IP $remote_addr;

upstream安装lamp

通过upstream端抓包tcpdump -i eth0 -nn -X tcp port 80 

查看客户端发来的IP地址,仍然是代理端:tail -fn 10 /var/log/httpd/access.log 

修改配置文件vim /etc/httpd/conf/httpd.conf

      LogFormat %h------>%{X-Real-IP}i

      service httpd reload

      查看:tail -fn 10 /var/log/httpd/access.log 


upstream模块


与proxy模块结合使用的模块中,最常用的当属upstream模块。upstream模块可定义一个新的上下文,它包含了一组宝岛upstream服务器,这些服务器可能被赋予了不同的权重、不同的类型甚至可以基于维护等原因被标记为down。


upstream模块常用的指令有:

ip_hash:基于客户端IP地址完成请求的分发,它可以保证来自于同一个客户端的请求始终被转发至同一个upstream服务器;

keepalive:每个worker进程为发送到upstream服务器的连接所缓存的个数;

least_conn:最少连接调度算法;

server:定义一个upstream服务器的地址,还可包括一系列可选参数,如:

weight:权重;

max_fails:最大失败连接次数,失败连接的超时时长由fail_timeout指定;

fail_timeout:等待请求的目标服务器发送响应的时长;

backup:用于fallback的目的,所有服务均故障时才启动此服务器;

down:手动标记其不再处理任何请求;


变量:

$upstream_addr:上游服务器的地址

$upstream_cache_status命中缓存信息

$upstream_status状态码



例如:

upstream backend {

 server www.magedu.com weight=5;

 server www2.magedu.com:8080       max_fails=3  fail_timeout=30s;

}


upstream模块的负载均衡算法主要有三种,轮调(round-robin)、ip哈希(ip_hash)和最少连接(least_conn)三种。


此外,upstream模块也能为非http类的应用实现负载均衡,如下面的示例定义了nginx为memcached服务实现负载均衡之目的。

注意:backup与ip_hash没有作用,都宕机了怒会自动转到backup上去。

      down与IP_hash有意义


upstream memcachesrvs {

server 172.16.100.6:11211;

server 172.16.100.7:11211;

}

server {

location / {

set $memcached_key "$uri?$args";

memcached_pass memcachesrvs;

error_page 404 = @fallback;

}

location @fallback {

  proxy_pass http://127.0.0.1:8080;

}

}


add_head是代理服务器发往客户端的首部

server {

        listen       80;

        server_name  www.magedu.com;

        add_header X-Via $server_addr;

wKioL1ZBXquRqtg3AAH9JRed7No307.jpg


缓冲区设定


nginx在默认情况下在将其响应给客户端之前会尽可能地接收来upstream服务器的响应报文,它会将这些响应报文存暂存于本地并尽量一次性地响应给客户端。然而,在来自于客户端的请求或来自upsteam服务器的响应过多时,nginx会试图将之存储于本地磁盘中,这将大大降低nginx的性能。因此,在有着更多可用内存的场景中,应该将用于暂存这些报文的缓冲区调大至一个合理的值。


1.proxy_buffer_size size:设定用于暂存来自于upsteam服务器的第一个响应报文的缓冲区大小;

2.proxy_buffering on|off:启用缓冲upstream服务器的响应报文,否则,如果proxy_max_temp_file_size指令的值为0,来自upstream服务器的响应报文在接收到的那一刻将同步发送至客户端;一般情况下,启用proxy_buffering并将proxy_max_temp_file_size设定为0能够启用缓存响应报文的功能,并能够避免将其缓存至磁盘中;

3.proxy_buffers 8 4k|8k:用于缓冲来自upstream服务器的响应报文的缓冲区大小;


缓存


nginx做为反向代理时,能够将来自upstream的响应缓存至本地,并在后续的客户端请求同样内容时直接从本地构造响应报文。


1.proxy_cache zone|off:定义一个用于缓存的共享内存区域,其可被多个地方调用;缓存将遵从upstream服务器的响应报文首部中关于缓存的设定,如 "Expires"、"Cache-Control: no-cache"、 "Cache-Control: max-age=XXX"、"private"和"no-store" 等,但nginx在缓存时不会考虑响应报文的"Vary"首部。为了确保私有信息不被缓存,所有关于用户的私有信息可以upstream上通过"no-cache" or "max-age=0"来实现,也可在nginx设定proxy_cache_key必须包含用户特有数据如$cookie_xxx的方式实现,但最后这种方式在公共缓存上使用可能会有风险。因此,在响应报文中含有以下首部或指定标志的报文将不会被缓存。

Set-Cookie

Cache-Control containing "no-cache", "no-store", "private", or a "max-age" with a non-numeric or 0 value

Expires with a time in the past

X-Accel-Expires: 0

2.proxy_cache_key:设定在存储及检索缓存时用于“键”的字符串,可以使用变量为其值,但使用不当时有可能会为同一个内容缓存多次;另外,将用户私有信息用于键可以避免将用户的私有信息返回给其它用户;

3.proxy_cache_lock:启用此项,可在缓存未命令中阻止多个相同的请求同时发往upstream,其生效范围为worker级别;

4.proxy_cache_lock_timeout:proxy_cache_lock功能的锁定时长;

5.proxy_cache_min_uses:某响应报文被缓存之前至少应该被请求的次数;

6.proxy_cache_path:定义一个用记保存缓存响应报文的目录,及一个保存缓存对象的键及响应元数据的共享内存区域(keys_zone=name:size),其可选参数有:

levels:每级子目录名称的长度,有效值为1或2,每级之间使用冒号分隔,最多为3级;1级是16,2极256;

inactive:缓存空间,非活动缓存项从缓存中剔除之前的最大缓存时长;

max_size:缓存空间(目录)大小的上限,当需要缓存的对象超出此空间限定时,缓存管理器将基于LRU算法对其进行清理;

loader_files:缓存加载器(cache_loader)的每次工作过程最多为多少个文件加载元数据;

loader_sleep:缓存加载器的每次迭代工作之后的睡眠时长;

loader_threashold:缓存加载器的最大睡眠时长;

例如:  proxy_cache_path  /data/nginx/cache/one    levels=1      keys_zone=one:10m;

proxy_cache_path  /data/nginx/cache/two    levels=2:2    keys_zone=two:100m;

proxy_cache_path  /data/nginx/cache/three  levels=1:1:2  keys_zone=three:1000m;

7.proxy_cache_use_stale:在无法联系到upstream服务器时的哪种情形下(如error、timeout或http_500等)让nginx使用本地缓存的过期的缓存对象直接响应客户端请求;其格式为:

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_404 | off 

8.proxy_cache_valid [ code ...] time:用于为不同的响应设定不同时长的有效缓存时长,例如:9、9.proxy_cache_valid  200 302  10m;

10.proxy_cache_methods [GET HEAD POST]:为哪些请求方法启用缓存功能;

11.proxy_cache_bypass string:设定在哪种情形下,nginx将不从缓存中取数据;例如:

        proxy_cache_bypass $cookie_nocache $arg_nocache $arg_comment;

 proxy_cache_bypass $http_pragma $http_authorization;


使用示例


http {

    proxy_cache_path  /data/nginx/cache  levels=1:2    keys_zone=STATIC:10m

                                         inactive=24h  max_size=1g;

    server {

        location / {

            proxy_pass             http://www.magedu.com;

            proxy_set_header       Host $host;

            proxy_cache            STATIC;

            proxy_cache_valid      200  1d;

            proxy_cache_valid   301 302 10m;

            proxy_cache_vaild   any 1m;

            proxy_cache_use_stale  error timeout invalid_header updating

                                   http_500 http_502 http_503 http_504;

        }

    }

}


wKiom1ZBiI-Rzt_lAAAG3rLnADM639.jpg

[root@node1 ~]# vim /etc/nginx/nginx.conf

 24     fastcgi_cache_path /cache/fastcgi/ levels=1:1 keys_zone=fcgi    cache:10m inactive=3m max_size=1g;

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

 55     location ~ \.php$ {

 56         fastcgi_cache_valid 200 1d;

 57         fastcgi_cache_valid 301 302 10m;

 58          fastcgi_cache_valid any 1m;

 59         fastcgi_cache_use_stale error timeout invalid_header htt    p_500;

 60         fastcgi_cache   fcgicache;

 61         root   /usr/share/nginx/html;

 62         fastcgi_pass   127.0.0.1:9000;

 63         fastcgi_index  index.php;

 64         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_    name;

 65         include        fastcgi_params;

 66         fastcgi_cache_key $request_method://$host$request_uri;

 67         add_header X-Cache $upstream_cache_status;

 68         add_header X-via $server_addr;

 69 }

[root@node1 ~]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node1 ~]# service nginx reload

重新载入 nginx:                                           [确定]

[root@node1 ~]# 

wKioL1ZBiW-BlpiSAAHpl1uX3tM293.jpg

[root@node1 ~]# vim /etc/nginx/conf.d/default.conf

 14     location /forum/ {

 15         proxy_cache_valid 200 1d;

 16         proxy_cache_valid 301 302 10m;

 17         proxy_cache_valid any 1m;

 18         proxy_cache_use_stale error timeout http_500 http_502 ht    tp_503 http_504;

 19         proxy_cache mycache;

 20         proxy_pass http://upservers/;

 21         proxy_set_header Host $host;

 22         proxy_set_header X-Real-IP $remote_addr;

 23  add_header x-Via $server_addr;

 24 add_header X-Cache $upstream_cache_status;

 25    }

wKiom1ZBjaSSBYK2AAIzSL68AdE843.jpg

------------------------------------------------------------------------------------------

源码安装lnmmp

源码安装mysql

[root@node200 ~]# mkdir /mydata/data -pv

mkdir: 已创建目录 "/mydata"

mkdir: 已创建目录 "/mydata/data"

[root@node200 ~]# useradd -r mysql

[root@node200 ~]# chown -R mysql.mysql /mydata/data/

[root@node200 ~]# tar xf mariadb-10.0.10-linux-x86_64.tar.gz -C /usr/local/

[root@node200 ~]# cd /usr/local/

[root@node200 local]# ls

bin  games    lib    libexec                       sbin   src

etc  include  lib64  mariadb-10.0.10-linux-x86_64  share

[root@node200 local]# ln -sv mariadb-10.0.10-linux-x86_64 mysql

"mysql" -> "mariadb-10.0.10-linux-x86_64"

[root@node200 local]# cd mysql

[root@node200 mysql]# ls

bin             data            lib         scripts        TODO

COPYING         docs            man         share

COPYING.LESSER  include         mysql-test  sql-bench

CREDITS         INSTALL-BINARY  README      support-files

[root@node200 mysql]# chown -R root.mysql ./*

[root@node200 mysql]# ll

总用量 204

drwxr-xr-x.  2 root mysql  4096 11月 11 00:54 bin

-rw-r--r--.  1 root mysql 17987 3月  31 2014 COPYING

-rw-r--r--.  1 root mysql 26545 3月  31 2014 COPYING.LESSER

-rw-r--r--.  1 root mysql  1553 3月  31 2014 CREDITS

drwxr-xr-x.  3 root mysql  4096 11月 11 00:53 data

drwxr-xr-x.  2 root mysql  4096 11月 11 00:54 docs

drwxr-xr-x.  3 root mysql  4096 11月 11 00:54 include

-rw-r--r--.  1 root mysql  8694 3月  31 2014 INSTALL-BINARY

drwxr-xr-x.  3 root mysql  4096 11月 11 00:54 lib

drwxr-xr-x.  4 root mysql  4096 11月 11 00:53 man

drwxr-xr-x. 11 root mysql  4096 11月 11 00:54 mysql-test

-rw-r--r--.  1 root mysql 90897 3月  31 2014 README

drwxr-xr-x.  2 root mysql  4096 11月 11 00:54 scripts

drwxr-xr-x. 27 root mysql  4096 11月 11 00:54 share

drwxr-xr-x.  4 root mysql  4096 11月 11 00:54 sql-bench

drwxr-xr-x.  4 root mysql  4096 11月 11 00:53 support-files

-rw-r--r--.  1 root mysql  2311 3月  31 2014 TODO

[root@node200 mysql]# scripts/mysql_install_db --user=mysql --datadir=/mydata/data/


注意:安装mariadb-10.1.10-linux-x86_64.tar.gz要安装以下插件

rpm -ivh http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm

yum -y install jemalloc


[root@node200 mysql]# mkdir /etc/mysql

[root@node200 mysql]# cp support-files/my-large.cnf /etc/mysql/my.cnf

[root@node200 ~]# cd /usr/local/mysql/

[root@node200 mysql]# cp support-files/mysql.server /etc/rc.d/init.d/mysqld

[root@node200 mysql]# chmod +x /etc/rc.d/init.d/mysqld

[root@node200 mysql]# chkconfig --add mysqld

[root@node200 mysql]# vim /etc/mysql/my.cnf

 42 thread_concurrency = 8

 43 datadir = /mydata/data

 44 innodb_file_per_table = ON

   skip_name_resolve = ON

[root@node200 mysql]# service mysqld start

Starting MySQL.                                            [确定]


echo "export PATH=/usr/local/mysql/bin:$PATH" >> /etc/profile.d/mysql.sh && source /etc/profile.d/mysql.sh


ln -sv /usr/local/mysql/include/ /usr/include/mysql


vim /etc/ld.so.conf.d/mysql.conf

/usr/local/mysql/lib

-----------------------------------------------------------------------------

安装php

[root@node200 ~]# ls

anaconda-ks.cfg                      php-5.4.7.tar.gz  文档

epel-release-latest-6.noarch.rpm     公共的            下载

install.log                          模板              音乐

install.log.syslog                   视频              桌面

mariadb-10.0.10-linux-x86_64.tar.gz  图片

[root@node200 ~]# tar xf php-5.4.7.tar.gz 

[root@node200 ~]# cd php-5.4.7

[root@node200 php-5.4.7]# ls

[root@node200 ~]# ls

anaconda-ks.cfg                      php-5.4.7.tar.gz  文档

epel-release-latest-6.noarch.rpm     公共的            下载

install.log                          模板              音乐

install.log.syslog                   视频              桌面

mariadb-10.0.10-linux-x86_64.tar.gz  图片

[root@node200 ~]# tar xf php-5.4.7.tar.gz 

[root@node200 ~]# cd php-5.4.7

[root@node200 php-5.4.7]# ls

[root@node200 php-5.4.7]# yum install libmcrypt-devel libcurl* -y

[root@node200 php-5.4.7]# yum install mhash-devel -y

[root@node200 php-5.4.7]# yum install bzip2-devel -y

[root@node200 php-5.4.7]# yum install gd-devel -y

[root@node200 php-5.4.7]# yum groupinstall Desktop Platform Development -y

[root@node200 php-5.4.7]# yum install libxml2-devel -y

[root@node200 php-5.4.7]# yum install openssl-devel -y

[root@node200 php-5.4.7]# ./configure --prefix=/usr/local/php --with-mysql=/usr/local/mysql --with-openssl --enable-fpm --enable-sockets --enable-sysvshm  --with-mysqli=/usr/local/mysql/bin/mysql_config --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib-dir --with-libxml-dir=/usr --enable-xml  --with-mhash --with-mcrypt  --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2 --with-curl 

[root@node200 php-5.4.7]# make && make install

[root@node200 php-5.4.7]# cp php.ini-production /etc/php.ini

[root@node200 php-5.4.7]# cp sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm

[root@node200 php-5.4.26]# chmod +x /etc/rc.d/init.d/php-fpm

[root@node200 php-5.4.7]# chkconfig --add php-fpm

[root@node200 php-5.4.26]# cd /usr/local/php/etc/

[root@node200 etc]# cp php-fpm.conf.default php-fpm.conf

[root@node200 etc]# vim php-fpm.conf

 25 pid = /usr/local/php/var/run/php-fpm.pid

 32 error_log = /var/log/php-fpm.log

217 pm.max_children = 128

222 pm.start_servers = 5

227 pm.min_spare_servers = 2

232 pm.max_spare_servers = 5

243 pm.max_requests = 500

342 pm.status_path = /status

354 ping.path = /ping

359 ping.response = pong

440 rlimit_files = 10240

[root@node200 etc]# service php-fpm restart

Gracefully shutting down php-fpm . done

Starting php-fpm  done

[root@node200 etc]# ss -tanl | grep 9000

LISTEN     0      128               127.0.0.1:9000                     *:*  



***************************************************************

三台使用 整合nginx与PHP


  1.nginx服务器建立网页文件存放目录/www,并修改其权限:


1 mkdir /www

2 chown -R nginx:nginx /www

  2.修改nginx配置文件:


 1 vim /etc/nginx/nginx.conf

 2 --------------------------------------

 3 location / {

 4             root   /www;

 5             index  index.php index.html index.htm;

 6         }

 7 

 8 location ~ \.php$ {

 9             root           /www;

10             fastcgi_pass   192.168.0.130:9000;

11             fastcgi_index  index.php;

12             fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

13             include        fastcgi_params;

14         }

 

  3.修改fastcgi_params文件为:


 1 fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;

 2 fastcgi_param  SERVER_SOFTWARE    nginx;

 3 fastcgi_param  QUERY_STRING       $query_string;

 4 fastcgi_param  REQUEST_METHOD     $request_method;

 5 fastcgi_param  CONTENT_TYPE       $content_type;

 6 fastcgi_param  CONTENT_LENGTH     $content_length;

 7 fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

 8 fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

 9 fastcgi_param  REQUEST_URI        $request_uri;

10 fastcgi_param  DOCUMENT_URI       $document_uri;

11 fastcgi_param  DOCUMENT_ROOT      $document_root;

12 fastcgi_param  SERVER_PROTOCOL    $server_protocol;

13 fastcgi_param  REMOTE_ADDR        $remote_addr;

14 fastcgi_param  REMOTE_PORT        $remote_port;

15 fastcgi_param  SERVER_ADDR        $server_addr;

16 fastcgi_param  SERVER_PORT        $server_port;

17 fastcgi_param  SERVER_NAME        $server_name;

  4.在PHP服务器上,建立nginx用户,要保证和nginx服务器上的nginx用户id号、组id号一致:

  5.修改php-fpm配置文件,并重启:

1 vim /usr/local/php/etc/php-fpm.conf

2 ---------------------------------------------

3 listen = 192.168.0.130:9000         //监听物理网卡地址,供其它机器调用

4 user = nginx                           //php-fpm以nginx用户运行

5 group = nginx

6 ---------------------------------------------

7 service php-fpm restart

  6.在PHP服务器上创建/www目录,并开启nfs服务:

yum install nfs* -y

1 mkdir /www

2 chown -R nginx:nginx /www

3 vim /etc/exports

4 ---------------------------------------------

5 /www    192.168.19.0/24(rw,no_root_squash)

6 ---------------------------------------------

7 service nfs start

service rpcbind start

复制代码

  7.nginx服务器挂载nfs文件,并测试php,测试成功后删除index.php:

yum install nfs* -y

1 mount -t nfs 192.168.19.92:/www /www

2 vim /www/index.php

3 ---------------------------------------

4 <?php

5      phpinfo();

6 ?>

7 --------------------------------------

8 service nginx restart


整合PHP与MYSQL


  在mysql服务器上创建php服务器能够访问的数据库和用户:


1 /usr/local/mysql/bin/mysql

2 --------------------------------------------

3 CREATE DATABASE wordpress;

4 GRANT ALL ON wordpress.* TO 'wordpress'@'192.168.19.92' IDENTIFIED BY '123456';

5 FLUSH PRIVILEGES;


安装wordpress

  1.在/www文件夹下放入网页文件


  2.访问http://192.168.19.83,并按提示进行安装,配置没问题则会安装成功




为php安装xcache


  1.解压并安装:


1 tar xf xcache-3.2.0.tar.gz 

2 cd xcache-3.2.0

3 /usr/local/php/bin/phpize

4 ./configure --enable-xcache --with-php-config=/usr/local/php/bin/php-config

5 make && make install

    完成后,会出现:Installing shared extensions:    /usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/


  2.加载模块:


1 vim /etc/php.ini

2 -----------------------------------

3 extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/xcache.so        //找到extension配置的地方,加上此句


php安装memcache


  1.解压并安装:


1 tar xf memcache-2.2.7.tgz 

2 cd memcache-2.2.7

3 /usr/local/php/bin/phpize

4  ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache

5 make && make install

    完成后,会出现:Installing shared extensions:    /usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/


  2.加载模块:


1 vim /etc/php.ini

2 -----------------------------------

3 extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20131226/memcache.so        //找到extension配置的地方,加上此句



  3.两个加速模块都安装完毕,重启php-fpm:


1 service php-fpm restart

***********************************************************************************



[root@node200 etc]# vim /etc/nginx/conf.d/default.conf

 40     location ~ \.php$ {

 41         root           html;

 42         fastcgi_pass   127.0.0.1:9000;

 43         fastcgi_index  index.php;

 44         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;

 45         include        fastcgi_params;

 46     }

[root@node200 etc]# vim /etc/nginx/fastcgi_params

  1 fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;

  2 fastcgi_param  SERVER_SOFTWARE    nginx;

  3 fastcgi_param  QUERY_STRING       $query_string;

  4 fastcgi_param  REQUEST_METHOD     $request_method;

  5 fastcgi_param  CONTENT_TYPE       $content_type;

  6 fastcgi_param  CONTENT_LENGTH     $content_length;

  7 fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script    _name;

  8 fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;

  9 fastcgi_param  REQUEST_URI        $request_uri;

 10 fastcgi_param  DOCUMENT_URI       $document_uri;

 11 fastcgi_param  DOCUMENT_ROOT      $document_root;

 12 fastcgi_param  SERVER_PROTOCOL    $server_protocol;

 13 fastcgi_param  REMOTE_ADDR        $remote_addr;

 14 fastcgi_param  REMOTE_PORT        $remote_port;

 15 fastcgi_param  SERVER_ADDR        $server_addr;

 16 fastcgi_param  SERVER_PORT        $server_port;

 17 fastcgi_param  SERVER_NAME        $server_name;

[root@node200 etc]# service nginx restart

停止 nginx:                                               [确定]

正在启动 nginx:  

[root@node200 etc]# vim /etc/nginx/conf.d/default.conf

 15     location / {

 16         root   /usr/share/nginx/html;

 17         index index.php index.html index.htm;

 18     } 

 41         root           /node200/zye.com;

[root@node200 etc]# vim /etc/nginx/conf.d/default.conf

[root@node200 etc]# mkdir /node200/zye.com/ -pv

mkdir: 已创建目录 "/node200"

mkdir: 已创建目录 "/node200/zye.com/"

[root@node200 etc]# vim /node200/zye.com/index.php

  1 <h1>node200.zye.com</h1>

  2 <?php

  3 phpinfo();

  4 ?>

wKioL1ZDWhfjxUY8AAIw8J-apy0432.jpg


fastcgi模块的常用指令

  1. 1.fastcgi_pass: 指定fastcgi服务监听端口、地址;也支持使用Unix sock;

  2. fastcgi_bind: 指定联系fpm服务时使用的地址;

  3. fastcgi_param: 定义传递给fpm服务器的参数;

  4. fastcgi_index: php的主页面文件;

  5. 定义缓存路径跟proxy相同

Syntax:fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

Default:

Context:http

Sets the path and other parameters of a cache. Cache data are stored in files. Both the key and file name in a cache are a result of applying the MD5 function to the proxied URL. The levels parameter defines hierarchy levels of a cache. For example, in the following configuration


fastcgi_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

file names in a cache will look like this:


/data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c


6.  调用缓存

Syntax:fastcgi_cache zone | off;

Default:fastcgi_cache off;

Context:http, server, location

Defines a shared memory zone used for caching. The same zone can be used in several places. Parameter value can contain variables (1.7.9). The off parameter disables caching inherited from the previous configuration level.


[root@node200 etc]# ab -n 1000 -c 100 http://node200.zye.com/index.php

This is ApacheBench, Version 2.3 <$Revision: 655654 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Licensed to The Apache Software Foundation, http://www.apache.org/


Benchmarking node200.zye.com (be patient)

Completed 100 requests

Completed 200 requests

Completed 300 requests

Completed 400 requests

Completed 500 requests

Completed 600 requests

Completed 700 requests

Completed 800 requests

Completed 900 requests

Completed 1000 requests

Finished 1000 requests



Server Software:        nginx/1.0.15

Server Hostname:        node200.zye.com

Server Port:            80


Document Path:          /index.php

Document Length:        45328 bytes


Concurrency Level:      100

Time taken for tests:   2.301 seconds

Complete requests:      1000

Failed requests:        88

   (Connect: 0, Receive: 0, Length: 88, Exceptions: 0)

Write errors:           0

Total transferred:      45475900 bytes

HTML transferred:       45327900 bytes

Requests per second:    434.58 [#/sec] (mean)

Time per request:       230.109 [ms] (mean)

Time per request:       2.301 [ms] (mean, across all concurrent requests)

Transfer rate:          19299.54 [Kbytes/sec] received


Connection Times (ms)

              min  mean[+/-sd] median   max

Connect:        0    3   9.8      0      37

Processing:    22  215  30.2    222     247

Waiting:        4  214  31.1    222     245

Total:         52  218  23.9    222     277


Percentage of the requests served within a certain time (ms)

  50%    222

  66%    225

  75%    226

  80%    227

  90%    232

  95%    234

  98%    244

  99%    259

 100%    277 (longest request)

 

[root@node200 etc]# vim /etc/nginx/nginx.conf                                             

 29  fastcgi_cache_path /cache/fastcgi levels=1:2 keys_zone=fcgi:50

    m max_size=1g inactive=12h;

[root@node200 etc]# vim /etc/nginx/conf.d/default.conf

 40     location ~ \.php$ {

 41         root           /node200/zye.com;

 42         fastcgi_cache   fcgi;

 43         fastcgi_cache_valid 200 1h;

 44         fastcgi_cache_valid 301 302 5m; 45         fastcgi_cache_valid any 1m; 46         fastcgi_pass   127.0.0.1:9000; 47         fastcgi_index  index.php; 48         fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script    _name;  

 49         include        fastcgi_params;

 50     }

[root@node200 etc]# mkdir /cache/fastcgi -pv && chown -R nginx.nginx /cache/fastcgi

mkdir: 已创建目录 "/cache"

mkdir: 已创建目录 "/cache/fastcgi"

[root@node200 etc]# service nginx configtest

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node200 etc]# service nginx reload

重新载入 nginx:                                           [确定]

wKiom1ZDaufgp-3rAAI4RKoqzuo343.jpg

[root@node200 etc]# ab -n 1000 -c 100 http://node200.zye.com/index.php

This is ApacheBench, Version 2.3 <$Revision: 655654 $>

Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Licensed to The Apache Software Foundation, http://www.apache.org/


Benchmarking node200.zye.com (be patient)

Completed 100 requests

Completed 200 requests

Completed 300 requests

Completed 400 requests

Completed 500 requests

Completed 600 requests

Completed 700 requests

Completed 800 requests

Completed 900 requests

Completed 1000 requests

Finished 1000 requests



Server Software:        nginx/1.0.15

Server Hostname:        node200.zye.com

Server Port:            80


Document Path:          /index.php

Document Length:        45855 bytes


Concurrency Level:      100

Time taken for tests:   0.381 seconds

Complete requests:      1000

Failed requests:        0

Write errors:           0

Total transferred:      46003000 bytes

HTML transferred:       45855000 bytes

Requests per second:    2622.63 [#/sec] (mean)

Time per request:       38.130 [ms] (mean)

Time per request:       0.381 [ms] (mean, across all concurrent requests)

Transfer rate:          117821.03 [Kbytes/sec] received


Connection Times (ms)

              min  mean[+/-sd] median   max

Connect:        0    2   3.4      0      13

Processing:     9   35   8.2     37      46

Waiting:        0   34   8.8     37      46

Total:         20   36   5.5     37      47


Percentage of the requests served within a certain time (ms)

  50%     37

  66%     39

  75%     40

  80%     40

  90%     42

  95%     44

  98%     45

  99%     45

 100%     47 (longest request)

[root@node200 etc]# vim /etc/nginx/conf.d/default.conf

 40     location ~* \(status|ping) {

 41         root           /node200/zye.com;

 42         fastcgi_pass   127.0.0.1:9000;

 43         fastcgi_index  index.php;

 44         fastcgi_param  SCRIPT_FILENAME  $fastcgi_script_name;

 45         include        fastcgi_params;

 46 }

wKiom1ZDcNyiA90hAAEeXXIUEeY460.jpg

wKioL1ZEJQDjSX1BAAB7rXt7Avw314.jpg


php状态解释:

poolwww    进程池的名称;

process managerdynamic   进程管理器,有两种类型static和dynamic;

start time25/Apr/2014:15:28:07 +0800     起动php时间

start since2150     运行时长

accepted conn4021      已经接受的请求数;

listen queue0         等待队列中的请求的个数;

max listen queue90  fpm启动以来等待队列中请求的总数

listen queue len128   监听队列长度

idle processes4            空闲的进程数

active processes1   活动进程数

total processes5           总进程数

max active processes8   fpm启动以来最大活动进程数

max children reached0   达到最大子进程的次数

slow requests0           慢速请求的个数



-----------------------------------------------------------------------------------




Memcached

wKiom1ZOiaaRaswrAAEr_rSMjqA795.jpg


1.php程序自行找缓存,不跟mysql有关;

2.没有缓存,将去找mysql,然后在缓存到公共缓存。以便下次命中。

3.当memcache宕机,具体操作:

    (1)流量全down或者部分 

    (2)各服务器起来,预热缓存

    (3)将所有缓存放进来

Linux内存: 分配:malloc();

           释放:free();

memcache:slab allocator

Memcached是一款开源、高性能、分布式内存对象缓存系统,可应用各种需要缓存的场景,其主要目的是通过降低对Database的访问来加速web应用程序。它是一个基于内存的“键值对”key,value存储,key是通过hash比较,value用于存储数据库调用、API调用或页面引用结果的直接数据,如字符串、对象等。


Memcached是一款开发工具,它既不是一个代码加速器,也不是数据库中间件。其设计哲学思想主要反映在如下方面:

1. 简单key/value存储:服务器不关心数据本身的意义及结构,只要是可序列化数据即可。存储项由“键、过期时间、可选的标志及数据”四个部分组成;

2. 功能的实现一半依赖于客户端,一半基于服务器端:客户负责发送存储项至服务器端、从服务端获取数据以及无法连接至服务器时采用相应的动作;服务端负责接收、存储数据,并负责数据项的超时过期;

3. 各服务器间彼此无视:不在服务器间进行数据同步

4. O(1)的执行效率

5. 清理超期数据:默认情况下,Memcached是一个LRU缓存,同时,它按事先预订的时长清理超期数据;但事实上,memcached不会删除任何已缓存数据,只是在其过期之后不再为客户所见;而且,memcached也不会真正按期限清理缓存,而仅是当get命令到达时检查其时长


Memcached提供了为数不多的几个命令来完成与服务器端的交互,这些命令基于memcached的协议实现。

    分配术语:

        Page: 分配给slab(memcache内存空间)用于切割的内存空间,默认大小1MB;

        Chunk: 相当于每一个块,用户缓存记录的内存空间;

        slab class: 特定大小的chunk组;

        自定义增长因子(-f)

     

当有多台memcache时通过一致性hash算法来确定缓存到哪台缓存服务器

    (1)一致hash算法:对服务器取模,只要摸均衡,负载就均衡。

    (2)调度memcache,提高缓存命中率。

    (3)使用一致性hash;对服务器编排,进行名称或地址hsah码对2~32取余,并落在hash环上

    (4)数据对键hsah码的2~32取余,落在顺时针最近的缓存服务器上。

wKiom1ZOlo-jHXSCAAFLAmaJm4I885.jpg问题:节点不均衡(引入虚拟节点)

    (1)在每个服务器节点虚拟出一堆

    (2)将虚拟节点平均落在上面


    libevent库:epoll, poll, select

        

    memcached

        -l IP:监听的地址;

        -d: 运行为守护进程;

        -u: 以指定的身份运行;

        -m #: 缓存服务使用的内存空间;默认为64MB

        -c #:最大并发连接数,默认为1024;

        -p #: 监听的TCP端口,默认11211;

        -U #:监听的UDP端口,默认11211;0表示禁用;

        -M:内存耗尽时返回错误而非删除缓存对象;

        -f: 指定增长因子;默认为1.25;

        -n: chuck起始大小,key+value+flags,默认为48字节;

        -t: 单线程响应多请求,默认4个;

        -L: 使用大内存页,64位2兆,32 一般4K;

         

    存储类命令:set, add, replace, append, prepend

    获取数据类命令:get, delete, incr/decr

    统计类命令:stats, stats items, stats slabs, stats sizes

    清理命令: flush_all


----------------------------------------------------

安装memcached

[root@node120 ~]# yum install libevent\* -y

[root@node120 ~]# yum install memcached -y

[root@node120 ~]# rpm -ql memcached

/etc/rc.d/init.d/memcached

/etc/sysconfig/memcached

/usr/bin/memcached

/usr/bin/memcached-tool

/usr/share/doc/memcached-1.4.4

/usr/share/doc/memcached-1.4.4/AUTHORS

/usr/share/doc/memcached-1.4.4/CONTRIBUTORS

/usr/share/doc/memcached-1.4.4/COPYING

/usr/share/doc/memcached-1.4.4/ChangeLog

/usr/share/doc/memcached-1.4.4/NEWS

/usr/share/doc/memcached-1.4.4/README

/usr/share/doc/memcached-1.4.4/protocol.txt

/usr/share/doc/memcached-1.4.4/readme.txt

/usr/share/doc/memcached-1.4.4/threads.txt

/usr/share/man/man1/memcached.1.gz

/var/run/memcached

[root@node120 ~]# tail /etc/passwd | grep memca

memcached:x:496:493:Memcached daemon:/var/run/memcached:/sbin/nologin

[root@node120 ~]# memcached -u memcached

[root@node120 ~]# ss -tanl | grep 11211

LISTEN     0      128                      :::11211                   :::*     

LISTEN     0      128                       *:11211                    *:*  

[root@node120 ~]# ss -tunl | grep 11211

udp    UNCONN     0      0                      *:11211                 *:*     

udp    UNCONN     0      0                     :::11211                :::*     

tcp    LISTEN     0      128                   :::11211                :::*     

tcp    LISTEN     0      128                    *:11211                 *:*   

[root@node120 ~]# memcached -u memcached -f 1.1 -vv##########修改增长因子

[root@node120 ~]# vim /etc/sysconfig/memcached

PORT="11211"

USER="memcached"

MAXCONN="1024"

CACHESIZE="64"

OPTIONS=""

[root@node120 ~]# service memcached start

正在启动 memcached:                                       [确定]

[root@node120 ~]# telnet 127.0.0.1 11211    ##

Trying 127.0.0.1...

Connected to 127.0.0.1.

Escape character is '^]'.

stats

STAT pid 21831

STAT uptime 208    运行时间

STAT time 1447836866

STAT version 1.4.4

STAT pointer_size 64

STAT rusage_user 0.029995

STAT rusage_system 0.073988

STAT curr_connections 10

STAT total_connections 12

STAT connection_structures 11

STAT cmd_get 0

STAT cmd_set 0

STAT cmd_flush 0

STAT get_hits 0

STAT get_misses 0

STAT delete_misses 0

STAT delete_hits 0

STAT incr_misses 0

STAT incr_hits 0

STAT decr_misses 0

STAT decr_hits 0

STAT cas_misses 0

STAT cas_hits 0

STAT cas_badval 0

STAT auth_cmds 0

STAT auth_errors 0

STAT bytes_read 66

STAT bytes_written 28

STAT limit_maxbytes 67108864

STAT accepting_conns 1

STAT listen_disabled_num 0

STAT threads 4

STAT conn_yields 0

STAT bytes 0

STAT curr_items 0

STAT total_items 0

STAT evictions 0

END


add mykey 0 60 3

abc

STORED

get mykey

VALUE mykey 0 3

abc

END

get mykey

VALUE mykey 0 3

abc

END

get mykey

END

get mykey 0 3

END


LNMMP(在LNMP的基础上创建Memcached)

wKiom1ZNcIjAkxt8AAKOA3N7AiI610.jpg


[root@node200 ~]# ls

anaconda-ks.cfg                      php-5.4.26

apr-1.4.6                            php-5.4.26.tar.bz2

apr-1.4.6.tar.bz2                    公共的

apr-util-1.4.1.tar.bz2               模板

epel-release-latest-6.noarch.rpm     视频

httpd-2.4.6.tar.bz2                  图片

install.log                          文档

install.log.syslog                   下载

mariadb-10.0.10-linux-x86_64.tar.gz  音乐

memcache-2.2.7.tgz                   桌面

[root@node200 ~]# tar xf memcache-2.2.7.tgz       ##php主机安装 

[ro ot@node200 ~]# cd memcache-2.2.7

[root@node200 memcache-2.2.7]# /usr/local/php/bin/phpize

Configuring for:

PHP Api Version:         20100412

Zend Module Api No:      20100525

Zend Extension Api No:   220100525

[root@node200 memcache-2.2.7]# ./configure --with-php-config=/usr/local/php/bin/ph

phar        phar.phar   php         php-cgi     php-config  phpize

[root@node200 memcache-2.2.7]# ./configure --with-php-config=/usr/local/php/bin/php-config --enable-memcache

[root@node200 memcache-2.2.7]# make && make install

Installing shared extensions:     /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/

[root@node200 memcache-2.2.7]# vim /etc/php.ini

 717 ; Directory in which the loadable extensions (modules) reside.

 718 ; http://php.net/extension-dir

 719 ; extension_dir = "./"

 720 ; On windows:

 721 ; extension_dir = "ext"

 722   extension = /usr/local/php/lib/php/extensions/no-debug-non-zts-20100525/memcache.so

[root@node200 memcache-2.2.7]# service php-fpm  reload

Reload service php-fpm  done

wKiom1ZNe2SBbODoAAHr8CTFKsE311.jpg


[root@node200 memcache-2.2.7]# vim /node200/zye.com/memcache.php

  1 <?php

  2     $mem = new Memcache;

  3     $mem->connect("192.168.112.120", 11211)  or die("Could not connect    ");

  4 

  5     $version = $mem->getVersion();

  6     echo "Server's version: ".$version."<br/>\n";

  7 

  8     $mem->set('hellokey', 'Hello World', 0, 600) or die("Failed to sav

    e data at the memcached server");

  9     echo "Store data in the cache (data will expire in 600 seconds)<br    />\n";

 10 

 11     $get_result = $mem->get('hellokey');

 12     echo "$get_result is from memcached server.";         

 13 ?>

wKiom1ZNgQHiJF8pAADDPEtEdOg820.jpg


wKiom1ZNglXzAI5GAAAGh1izDvE171.jpg

[root@node120 ~]# telnet 127.0.0.1 11211

Trying 127.0.0.1...

Connected to 127.0.0.1.

Escape character is '^]'.

get hellokey

VALUE hellokey 0 11

Hello World

END


wKiom1ZNgpHgPt4wAAAGVkR_Vlc450.jpg

[root@node200 memcache-2.2.7]# cd /node200/zye.com/

[root@node200 zye.com]# mv memcache.php test.php

[root@node200 zye.com]# ls

index.php  test.php

[root@node200 ~]# ls

anaconda-ks.cfg                      package.xml

apr-1.4.6                            php-5.4.26

apr-1.4.6.tar.bz2                    php-5.4.26.tar.bz2

apr-util-1.4.1.tar.bz2               公共的

epel-release-latest-6.noarch.rpm     模板

httpd-2.4.6.tar.bz2                  视频

install.log                          图片

install.log.syslog                   文档

mariadb-10.0.10-linux-x86_64.tar.gz  下载

memcache-2.2.7                       音乐

memcache-2.2.7.tgz                   桌面

memcachephp.zip

[root@node200 ~]# unzip memcachephp.zip 

Archive:  memcachephp.zip

  inflating: memcache.php            

[root@node200 ~]# ls

anaconda-ks.cfg                      memcachephp.zip

apr-1.4.6                            package.xml

apr-1.4.6.tar.bz2                    php-5.4.26

apr-util-1.4.1.tar.bz2               php-5.4.26.tar.bz2

epel-release-latest-6.noarch.rpm     公共的

httpd-2.4.6.tar.bz2                  模板

install.log                          视频

install.log.syslog                   图片

mariadb-10.0.10-linux-x86_64.tar.gz  文档

memcache-2.2.7                       下载

memcache-2.2.7.tgz                   音乐

memcache.php                         桌面

[root@node200 ~]# mv memcache.php /node200/zye.com/

[root@node200 ~]# cd /node200/zye.com/

[root@node200 zye.com]# ls

index.php  memcache.php  test.php

[root@node200 zye.com]# vim memcache.php

 22 define('ADMIN_USERNAME','memcache');    // Admin Username

 23 define('ADMIN_PASSWORD','password');    // Admin Password

 24 define('DATE_FORMAT','Y/m/d H:i:s');

 25 define('GRAPH_SIZE',200);

 26 define('MAX_ITEM_DUMP',50);

 27  

 28 $MEMCACHE_SERVERS[] = '192.168.112.120:11211'; // add more as an array

 29 //$MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an array

wKiom1ZNhiLhADtyAAEv7HfG3DY589.jpg


wKioL1ZNiHSj3YyLAANBgaaQG4k568.jpg


wKiom1ZNglXzAI5GAAAGh1izDvE171.jpg

[root@node120 ~]# memcached-tool 192.168.112.120

  #  Item_Size  Max_age   Pages   Count   Full?  Evicted Evict_Time OOM

  1      96B     25633s       1       1      no        0        0    0

[root@node120 ~]# memcached-tool 192.168.112.120 stats

#192.168.112.120:11211 Field       Value

         accepting_conns           1

               auth_cmds           0

             auth_errors           0

                   bytes          85

              bytes_read         762-----用户发来的总字节数

           bytes_written       14766-----总发送的客户端响应的字节数

              cas_badval           0

                cas_hits           0

              cas_misses           0

               cmd_flush           0-----服务器,刷新

                 cmd_get          15-----服务器

                 cmd_set           8----服务器

             conn_yields           0

   connection_structures          11-----

        curr_connections          10-----当前连接数,尚未断开

              curr_items           1-----缓存条目个数

               decr_hits           0

             decr_misses           0

             delete_hits           0

           delete_misses           0

               evictions           0----多少次删缓存条目腾出空间

                get_hits          11---get命令,命中

              get_misses           4---get命令,未命中

               incr_hits           0

             incr_misses           0

          limit_maxbytes    67108864-----内存大小

     listen_disabled_num           0

                     pid        2871-----pid

            pointer_size          64-----多少位系统

           rusage_system    2.086682-----进程的内核运行时间

             rusage_user    0.578911-----进程的累计用户时间

                 threads           4-----线程数

                    time  1447922433-----1970/1/1,当前系统时间戳

       total_connections          39-----总的连接数

             total_items           8-----总的缓存条目

                  uptime       26239----运行时长

                 version       1.4.4


wKioL1ZNkFXDLXZUAAAGVniK5OA133.jpg

[root@node200 zye.com]# yum install phpMemcachedAdmin\* -y

[root@node200 zye.com]# mkdir pma

[root@node200 zye.com]# ls

index.php  memcache.php  pma  test.php

[root@node200 pma]# ln -s /usr/share/phpMemcachedAdmin/* .

[root@node200 pma]# ls

commands.php  configure.php  index.php  Library  Public  stats.php  View

wKiom1ZNvSST-jTsAADSrz_Fs3c317.jpg

wKiom1ZNv3eQ_h22AASAisOsEJk182.jpg


wKioL1ZNkFXDLXZUAAAGVniK5OA133.jpg

[root@node200 zye.com]# unzip memadmin-master.zip

[root@node200 zye.com]# ls

index.php  memadmin-master  memadmin-master.zip  memcache.php  pma  test.php

wKioL1ZNzHmi4TuTAAFIf2tKEtk797.jpgwKiom1ZNzIqwHeHMAAKDiM7wTFg083.jpgwKioL1ZNzSGyPE_WAAUiH8jTSss316.jpgwKioL1ZNzUeBQpHOAAUt3aZK3xI734.jpg

--------------------------------------------------------------------------------------


Nginx替代反向代理的缓存


解释:

Syntax:memcached_pass address;--

Default:

Context:location, if in location

Sets the memcached server address. The address can be specified as a domain name or an address, and a port:


Syntax:memcached_read_timeout time; 定义从memcached服务器读取响应超时。

Default:

memcached_read_timeout 60s;

Context:http, server, location

Defines a timeout for reading a response from the memcached server. The timeout is set only between two successive read operations, not for the transmission of the whole response. If the memcached server does not transmit anything within this time, the connection is closed.


Syntax:memcached_send_timeout time; 设置发送请求到memcached服务器超时。

Default:

memcached_send_timeout 60s;

Context:http, server, location

Sets a timeout for transmitting a request to the memcached server. The timeout is set only between two successive write operations, not for the transmission of the whole request. If the memcached server does not receive anything within this time, the connection is closed.


Syntax:memcached_send_timeout time;

Default:

memcached_send_timeout 60s;

Context:http, server, location

Sets a timeout for transmitting a request to the memcached server. The timeout is set only between two successive write operations, not for the transmission of the whole request. If the memcached server does not receive anything within this time, the connection is closed.


Syntax:memcached_next_upstream error | timeout | invalid_response | not_found | off ...;当发生故障,跳转下一台memcached服务器

Default:

memcached_next_upstream error timeout;

Context:http, server, location

Specifies in which cases a request should be passed to the next server:

error

an error occurred while establishing a connection with the server, passing a request to it, or reading the response header;

timeout

a timeout has occurred while establishing a connection with the server, passing a request to it, or reading the response header;

invalid_response

a server returned an empty or invalid response;

not_found

a response was not found on the server;

off

disables passing a request to the next server.


-----------------------------------------------------------------------


Nginx整合memcached:

先找缓存在在找后端服务器

server {

    location / {

        set $memcached_key "$uri?$args";

        memcached_pass host:11211;

        error_page     404 502 504 = @fallback;

    }


    location @fallback {             ##定义fallback

        proxy_pass     http://backend;

    }

}


示例:

wKioL1ZNkFXDLXZUAAAGVniK5OA133.jpg

[root@node200 ~]# vim /etc/nginx/nginx.conf

 15      location / {

 16                 set $memcached_key "$uri$args";

 17                 memcached_pass     192.168.112.120:11211;

 18                 default_type       text/html; 

19                 error_page         404 502 504 = @fallback;    

 20 }    

 21  location @fallback {

 22                 proxy_pass http://192.168.112.120;

 23         }

 24     

 25     error_page  404              /404.html;

 26     location = /404.html {

 27         root   /usr/share/nginx/html;

 28     }

[root@node200 ~]# nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

nginx: configuration file /etc/nginx/nginx.conf test is successful

[root@node200 ~]# service nginx reload

重新载入 nginx: 

wKiom1ZN9OaxXTH6AACZ3IqDY1w075.jpg