Nginx+php+memcached+mysql+ip-hash do memcached cluster

Source: Internet
Author: User
Tags fpm memcached mysql query pkill



1, Nginx and memcached integration



#安装memcached支持的事务库libevent


wget https://github.com/libevent/libevent/releases/download/release-2.0.22-stable/ Libevent-2.0.22-stable.tar.gztar zxf libevent-2.0.22-stable.tar.gz CD libevent-2.0.22-stable./configure--prefix=/ Usr/local/libeventmake && make Installecho $?cd.


#接下来安装memcached:


wget Http://www.memcached.org/files/memcached-1.4.35.tar.gztar zxf memcached-1.4.35.tar.gzcd memcached-1.4.35./ Configure--prefix=/usr/local/memcached--with-libevent=/usr/local/libeventmake && make Installecho $?cd..


#运行memcached



[Email protected] ~]#/usr/local/memcached/bin/memcached-d-u nobody-vv



#配置nginx配置文件nginx. conf, locate the URI of the user and give memcached the cache



#添加location定位:


Location ~* User {set $memcached _key "$uri"; #设置memcached的key为uri memcached_pass 192.168.14 6.132:11,211; #链接memcached Error_page 404/callback.php; #错误定位}


#加载nginx配置



Nginx-s Reload



#在memcached中写入一条URI数据, test consolidation success


[[Email protected] ~]# telnet 192.168.146.132 11211Trying 192.168.146.132...Connected to 192.168.146.132.Escape Character is ' ^] '. add/user1.html 0 0 7iamlisi Storedquit


#访问http://192.168.146.132/user1.html If can see Iamlisi, then Nginx and memcache integration success!






2. Integrating PHP with memcahced



#安装PHP扩展模块memcache


wget Http://pecl.php.net/get/memcache-2.2.7.tgztar zxvf MEMCACHE-2.2.7.TGZCD memcache-2.2.7/usr/local/php/bin/ Phpize./configure--enable-memcache--with-php-config=/usr/local/php/bin/php-config--with-zlib-dirmake && Make Installecho $?CD.


Pkill php-fpm #杀死php-FPM Process



PHP-FPM #启动php-FPM



Http://192.168.146.132/test.php can see the Memcache module is successful.



#测试PHP与memcached


Vim/usr/local/nginx/html/callback.php<?phpprint_r ($_server);? >php


#访问http://1982.168.146.132/user2.html This URI does not exist in memcached, it will be called back to the callback.php processing request, the result is as follows:


Array (    [user] => nobody    [home] => /     [fcgi_role] => responder    [script_filename] = > /usr/local/nginx/html/callback.php    [QUERY_STRING] =>      [REQUEST_METHOD] => GET    [CONTENT_TYPE] =>      [CONTENT_LENGTH] =>     [SCRIPT_NAME] =>  /callback.php    [request_uri] => /user2.html    [ document_uri] => /callback.php    [document_root] => /usr/local/ Nginx/html    [server_protocol] => http/1.1    [request_ scheme] => http    [gateway_interface] => cgi/1.1     [server_software] => nginx/1.12.1    [remote_addr] => 192.168.146.1     [REMOTE_PORT] => 14187    [SERVER_ADDR] =>  192.168.146.132    [server_port] => 80    [server_name]  => localhost    [REDIRECT_STATUS] => 200     [HTTP_HOST] => 192.168.146.132    [HTTP_CONNECTION] =>  keep-alive    [http_upgrade_insecure_requests] => 1    [ http_user_agent] => mozilla/5.0  (windows nt 10.0; win64; x64)   applewebkit/537.36  (Khtml, like gecko)  Chrome/60.0.3112.113 Safari/537.36   &NBSP;&NBSP;[HTTP_ACCEPT]&NBSP;=&GT;&NBSP;TEXT/HTML,APPLICATION/XHTML+XML,APPLICATION/XML;Q=0.9,IMAGE/WEBP, Image/apng,*/*;q=0.8   &nbSp [http_accept_encoding] => gzip, deflate    [http_accept_language] = > zh-CN,zh;q=0.8    [PHP_SELF] => /callback.php    &NBSP;[REQUEST_TIME]&NBSP;=&GT;&NBSP;1503552110)


3, use PHP to let memcached link MySQL query key and value and deposit memcached,



#接下来我们写个PHP程序, link the database, so that memcached can not find the URI to the callback to PHP, and then PHP to link the database, find the data after the memcached:


Cat html/callback.php<?php//print_r ($_server);//Get UID used to do key$uri = $_server[' REQUEST_URI '];// Analyze the UID number in the UiR $uid = substr ($uri, 5,strpos ($uri, '. ') -5);//echo  $uid;//link database, Query and write Memcached$conn = mysql_connect (' localhost ', ' root ', ' 123.com '); $sql  =  ' use test '; mysql_query ($sql, $conn); $sql  =  ' Set names utf8 '; mysql_query ($ SQL, $conn); $sql  =  ' select * from user where uid= '. $uid; $rs  =  mysql_query ($sql, $conn);echo  ' from mysql query<br /> '; $user  = mysql_fetch_ Assoc ($rs);if  (Empty ($user))  {    echo  ' No this user ';}  else {//    print_r ($user);     $html  =  ' 



#此处我们要在数据库中建立test库和user表, and write the UID and uname field data:



#注意: callback.php file calls the library and table, the field to correspond to establish


Mysql> CREATE DATABASE test;mysql> use test;mysql> CREATE TABLE user (with UID int (one) not null, UNA Me varchar (255) NOT NULL,--primary key (UID));mysql> INSERT into user (Uid,uname) VALUES (1, ' I am memcached '); my sql> INSERT INTO User (Uid,uname) VALUES (2, ' DSLAJFFLSAJ;GLJDASLGJLAJFDALSJF ');


#此时访问uir, the first is forwarded to memcached processing, Memcached does not have a key callback to callback.php processing, and then the PHP link database, query URI data, and then memcached write key and value, and return the data to the client.



Http://192.168.146.132/user1.html



#memcached显示数据动态:


<36 New auto-negotiating client connection36:client using the ASCII protocol<36 add/user1.html 1 122>36 STO red<36 Connection closed.<36 New auto-negotiating client connection36:client using the ASCII protocol<36 get/us er1.html>36 sending key/user1.html>36 end<36 connection closed.


4, configure memcached, Nginx and PHP use a consistent hash (Ip-hash)



#当使用memcached群集时, the data write memcached inconsistency is encountered because Nginx mode accesses the memcached server using Round-robin (polling), which causes the problem of writing and reading data not on the same server. To this end, Nginx provides a Ip-hash IP-based consistent hashing algorithm that records access IP and the same IP accesses the last logged server the next time it accesses.



Official Reference Document: https://www.nginx.com/resources/wiki/modules/consistent_hash/



#下载nginx the hash module and install:


Cd/root/toolswget Https://github.com/replay/ngx_http_consistent_hash/archive/master.zipunzip Master.zip


#查看nginx编译参数


[Email protected] tools]# Nginx-vnginx version:nginx/1.8.1built by gcc 4.4.7 20120313 (Red Hat 4.4.7-18) (GCC) built WI Th OpenSSL 1.0.1e-fips each Feb 2013TLS SNI support enabledconfigure arguments:--user=nginx--group=nginx--prefix=/usr/loc Al/nginx--with-http_ssl_module--with-http_stub_status_module--with-http_ssl_module--add-module=/root/tools/ Nginx-1.8.1/nginx-rtmp-module


#进入nginx源码目录, add module installation


[Email protected] tools]# CD Nginx-1.8.1[[email protected] nginx-1.8.1]#./configure--user=nginx--group=nginx-- Prefix=/usr/local/nginx--with-http_ssl_module--with-http_stub_status_module--with-http_ssl_module--add-module= /root/tools/nginx-1.8.1/nginx-rtmp-module--add-module=/root/tools/ngx_http_consistent_hash-master/[[email Protected] nginx-1.8.1] #make && make install


#模拟memcache集群, differentiate Port start three memcached


memcached-d-U nobody-p 11211-vvmemcached-d-u nobody-p 11212-vvmemcached-d-u nobody-p 11213-vv


#nginx配置文件http段添加upstram模块:


Upstream Mcserver {consistent_hash $request _uri;        #指定使用哈希算法, for memcached, refer to document server 192.168.146.132:11211;        Server 192.168.146.132:11212;        Server 192.168.146.132:11213; }


#并在location中反向代理到mcserver集群:



Specific reference documents: Http://nginx.org/en/docs/http/ngx_http_memcached_module.html#memcached_pass


Location ~*/user {set $memcached _key "$uri";    #将uri配置为memcached的key Memcached_pass Mcserver;  #代理到memcached集群 error_page 404 =/callback.php; #memcached中找不到key将回调到此文件}


#重新加载nginx配置



Nginx-s Reload



#修改php配置为hash查询



#具体参考文挡: Http://cn2.php.net/manual/en/memcache.ini.php#ini.memcache.hash-strategy


Vim/usr/local/php/etc/php.inimemcache.hash_strategy=consistent #添加, using a consistent hash


#重新启动php-FPM


Pkill-9 Php-fpmnetstat-lntup|grep 9000PHP-FPM


#修改回调代码, set up memcached cluster links


Cat html/callback.php<?php//print_r ($_server);//Get UID used to do key$uri = $_server[' REQUEST_URI '];// Analyze the UID number in the UiR $uid = substr ($uri, 5,strpos ($uri, '. ') -5);//Establish memcached cluster link $mem = new memcache (); $mem->addserver (' 192.168.146.132 ', 11211); $mem- >addserver (' 192.168.146.132 ', 11212); $mem->addserver (' 192.168.146.132 ', 11213);//link database, query and write Memcached$conn  = mysql_connect (' localhost ', ' root ', ' 123.com '); $sql  =  ' use test '; mysql_query ($sql, $ conn); $sql  =  ' Set names utf8 '; mysql_query ($sql, $conn); $sql  =  ' select *  from user where uid= '. $uid; $rs  = mysql_query ($sql, $conn);echo  ' from  Mysql query<br /> '; $user  = mysql_fetch_assoc ($rs);if  (Empty ($user))  {     echo  ' No this user ';}  else {     $html  =  ' 
	


#测试数据, Memcached writes data and queries data on one port:


<36 new auto-negotiating client connection36: Client using the  Ascii protocol<36 get /user1.html>36 end<36 connection closed.<36  new auto-negotiating client connection36: client using the ascii  protocol<36 add /user1.html 0 10 87>36 STORED<37 new  Auto-negotiating client connection37: client using the ascii protocol<37  get /user1.html>37 END<37 connection closed.<40 new  Auto-negotiating client connection40: client using the ascii protocol<40  get /user2.html>40 END<40 connection closed.<40 new  Auto-negotiating client connection40: client using the ascii protocol<40  add /user2.html 0 10 40&Gt;40 stored<41 new auto-negotiating client connection41: client using  the ascii protocol<41 get /user2.html>41 END<41 connection  Closed.


#到此nginx +php+memcached+mysql and phenomenon memcached cluster consistent hashing algorithm complete!



#途中遇到一个问题: In MySQL write Chinese data, PHP call after the first display of normal, the second deposit memcached after the call is garbled, I use Google and Firefox browser is garbled, and with and IE is not garbled! Temporarily did not find the reason, have to know forgot to inform, extremely thanks!!!



This article is from the "Gen Y Rookie" blog, so be sure to keep this source http://zhangxinqi.blog.51cto.com/9668428/1961992



Nginx+php+memcached+mysql+ip-hash do memcached cluster


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.