PHP连接memcached
<?php $memcache = new Memcache; //创建一个memcache对象 $memcache->connect('localhost', 11211) or die ("Could not connect"); //连接Memcached服务器 $memcache->set('key', 'test'); //设置一个变量到内存中,名称是key 值是test $get_value = $memcache->get('key'); //从内存中取出key的值 echo $get_value; ?>
常用操作
<?php //连接Memcache $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(); ?>
在一台或者多台机器启用一个或者多个进程,这里是在一台机器启
用两个进程,使用两个端口:
#./memcached -d -u nobody -m 512 127.0.0.1 -p 11211
#./memcached -d -u nobody -m 512 127.0.0.1 -p 11212
<?php //连接Memcache $mem = new Memcache; $mem->addServer("localhost", 11211); $mem->addServer("localhost", 11212); //保存数据 $mem->set('key1', 'This is first 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->close(); ?>