friht 发表于 2018-10-7 14:48:42

nginx+PHP+memcached+MySQL+ip-hash做memcached集群

  1、nginx与memcached整合
  #安装memcached支持的事务库libevent
wget https://github.com/libevent/libevent/releases/download/release-2.0.22-stable/libevent-2.0.22-stable.tar.gz  
tar zxf libevent-2.0.22-stable.tar.gz
  
cd libevent-2.0.22-stable
  
./configure --prefix=/usr/local/libevent
  
make && make install
  
echo $?
  
cd ..
  #接下来安装memcached:
wget http://www.memcached.org/files/memcached-1.4.35.tar.gz  
tar zxf memcached-1.4.35.tar.gz
  
cd memcached-1.4.35
  
./configure --prefix=/usr/local/memcached --with-libevent=/usr/local/libevent
  
make && make install
  
echo $?
  
cd ..
  #运行memcached
  # /usr/local/memcached/bin/memcached -d -u nobody -vv
  #配置nginx配置文件nginx.conf,定位user的uri交给memcached做缓存
  #添加location定位:
location ~* user {  
                set $memcached_key "$uri"; #设置memcached的key为uri
  
                memcached_pass 192.168.146.132:11211; #链接memcached
  
                error_page 404 /callback.php; #错误定位
  
      }
  #加载nginx配置

  nginx -s>  #在memcached中写入一条URI数据,测试整合是否成功
# telnet 192.168.146.132 11211  
Trying 192.168.146.132...
  
Connected to 192.168.146.132.
  
Escape character is '^]'.
  
add /user1.html 0 0 7
  
iamlisi
  
STORED
  
quit
  #访问http://192.168.146.132/user1.html如能看到iamlisi,那么nginx与memcache整合成功了!
  2、整合PHP与memcahced
  #安装PHP扩展模块memcache
wget http://pecl.php.net/get/memcache-2.2.7.tgz  
tar zxvf memcache-2.2.7.tgz
  
cd memcache-2.2.7
  
/usr/local/php/bin/phpize
  
./configure --enable-memcache --with-php-config=/usr/local/php/bin/php-config --with-zlib-dir
  
make && make install
  
echo $?
  
cd ..
  pkill php-fpm   #杀死php-fpm进程
  php-fpm   #启动php-fpm
  http://192.168.146.132/test.php能看到memcache模块就成功了
  #测试PHP与memcached
vim /usr/local/nginx/html/callback.php  
php
  #访问http://1982.168.146.132/user2.html 此uri在memcached中不存在,就会回调到callback.php处理请求,结果如下:
Array  
(
  
    => nobody
  
    => /
  
    => RESPONDER
  
    => /usr/local/nginx/html/callback.php
  
    =>
  
    => GET
  
    =>
  
    =>
  
    => /callback.php
  
    => /user2.html
  
    => /callback.php
  
    => /usr/local/nginx/html
  
    => HTTP/1.1
  
    => http
  
    => CGI/1.1
  
    => nginx/1.12.1
  
    => 192.168.146.1
  
    => 14187
  
    => 192.168.146.132
  
    => 80
  
    => localhost
  
    => 200
  
    => 192.168.146.132
  
    => keep-alive
  
    => 1
  
    => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
  
    => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
  
    => gzip, deflate
  
    => zh-CN,zh;q=0.8
  
    => /callback.php
  
    => 1503552110
  
)
  3、使用PHP让memcached链接MySQL查询key与value并存入memcached,
  #接下来我们写个PHP程序,链接数据库,让memcached找不到的uri就回调给PHP,然后PHP去链接数据库,查找数据后给memcached:
cat html/callback.php  
页: [1]
查看完整版本: nginx+PHP+memcached+MySQL+ip-hash做memcached集群