一、Nginx连接Memcached:
用法:nginx响应请求时,通过key直接请求memcached,如果没有相应的内容,再回调PHP页面去查询db,并写入memcached
分析:memcached是k/v存储,nginx请求memecached时用什么做key?一般用 uri arg 做key, 如 /abc.php?id=3
对应的Nginx配置:
location / {
set $memcached_key $uri;
memcached_pass 127.0.0.1:11211;
error_page 404 /callback.php;
}
对应的PHP脚本:
<?php
$uri = $_SERVER['REQUEST_URI'];
$uid = substr($uri, 5, strpos($uri, '.')-5);
//连接数据库
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("use test");
$mysqli->query("set names utf8");
$result = $mysqli->query("select * from user where uid = '".$uid."'");
if ($result->num_rows > 0) {
$user = $result->fetch_array();
//将数据存进memcache
$mem = new memcache();
$mem->connect("localhost", 11211);
$mem->add($uri, $user['uname'], 0, 300);
$mem->close();
print_r($user);
} else {
echo "no this user";
}
?>
二、第3方模块编译及一致性哈希应用:
1.下载ngx_http_consistent_hash扩展模块:
wget https://github.com/replay/ngx_http_consistent_hash/archive/master.zip
2.将文件解压后复制到/opt/nginx/module下
3.切换到nginx编译文件夹,重新编译nginx:
./configure --prefix=/opt/nginx/ --add-module=/opt/nginx/module/ngx_http_consistent_hash-master/
make && make install
4.配置Memcached集群:
对应的nginx配置:
upstream memserver { //把用到的memcached节点,声明在一个组里
consistent_hash $request_uri; //通过一致性哈希算法将某一特定的key统一指定到某一台mc服务器
server192.168.61.132:11211; //这个地方使用localhost会出现问题
server192.168.61.132:11212;
server192.168.61.132:11213;
}
在PHP.ini中添加如下配置 :
memcache.hash_strategy=consistent
对应的PHP脚本:
<?php
$uri = $_SERVER['REQUEST_URI'];
$uid = substr($uri, 5, strpos($uri, '.')-5);
//连接数据库
$mysqli = new mysqli("localhost", "root", "", "test");
$mysqli->query("use test");
$mysqli->query("set names utf8");
$result = $mysqli->query("select * from user where uid = '".$uid."'");
if ($result->num_rows > 0) {
$user = $result->fetch_array();
//将数据存进memcache
$mem = new memcache();
//添加多台mc服务器
$mem->addServer("192.168.61.132", 11211);
$mem->addServer("192.168.61.132", 11212);
$mem->addServer("192.168.61.132", 11213);
$mem->add($uri, $user['uname'], 0, 300);
$mem->close();
print_r($user);
} else {
echo "no this user";
}
?>
监听memcached端口:
/usr/bin/memcached -u nobody -vv -p 11211
/usr/bin/memcached -u nobody -vv -p 11212
/usr/bin/memcached -u nobody -vv -p 11213
实验结果:
如下图所示,Nginx将user4.html页面转发给11211端口,并且PHP将数据缓存进11211端口,这样则实现了一致性哈希: