nginx (2)


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








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章