上一篇文章给大家介绍了memcached的安装以及简单的命令。这里给大家介绍php如何结合memcached。
配置其实很简单的就几步操作。
1. 先安装php的memcache扩展,相信大家对php的扩展模块安装不会陌生。
首先可以去pecl.php.net 官网下载安装包,我这里下载的2.2.5版本
# tar zxfmemcache-2.2.5.tgz
# cd memcache-2.2.5
# /usr/local/php/bin/phpize
# ./configure --with-php-config=/usr/local/php/bin/php-config
# make && make installl安装完后会有类似这样的提示:
Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20130626/
然后修改php.ini,把extension_dir = "./" 修改为
extension_dir = "/usr/local/php/extensions"并添加一行
extension="memcache.so"
然后创建目录 mkdir /usr/local/php/extensions
将no-debug-non-zts-20130626/目录下的memcache.so移到/usr/local/php/extensions/目录下
/usr/local/php/bin/php -m |grepmemcache 可以检验扩展模块是否添加成功。
2. php脚本测试
首先写一个测试的php脚本
vim test.php 内容如下:
<?php
$mem = new Memcache;
$mem->connect("localhost", 11211);
//保存数据
$mem->set(‘key1‘, ‘This is first value‘, 0, 60);
$val = $mem->get(‘key1‘);
echo "Get key1 value: " . $val ."<br>";
//替换数据
$mem->replace(‘key1‘, ‘This is replace value‘, 0, 60);
$val = $mem->get(‘key1‘);
echo "Get key1 value: " . $val . "<br>";
//保存数组数据
$arr = array(‘aaa‘, ‘bbb‘, ‘ccc‘, ‘ddd‘);
$mem->set(‘key2‘, $arr, 0, 60);
$val2 = $mem->get(‘key2‘);
echo "Get key2 value: ";
print_r($val2);
echo "<br>";
//删除数据
$mem->delete(‘key1‘);
$val = $mem->get(‘key1‘);
echo "Get key1 value: " . $val . "<br>";
//清除所有数据
$mem->flush();
$val2 = $mem->get(‘key2‘);
echo "Get key2 value: ";
print_r($val2);
echo "<br>";
//关闭连接
$mem->close();
?>
然后执行命令:/usr/local/php/bin/php test.php
看看能否得到如下内容:
Get key1 value: This is first value<br>Get key1 value: This is replace value<br>Get key2 value: Array
(
[0] => aaa
[1] => bbb
[2] => ccc
[3] => ddd
)
<br>Get key1 value: <br>Get key2 value: <br>
如果得到此内容说明结合成功。