Home > Backend Development > PHP Tutorial > Memcached之PHP调用

Memcached之PHP调用

WBOY
Release: 2016-06-23 13:56:10
Original
923 people have browsed it

通过PHP调用Memcahce,首先需要在服务器上安装Memcache,如何安装Memcache不是本文的重点,

关于memcache的安装,有兴趣的朋友请参考这里:http://blog.csdn.net/xifeijian/article/details/22000173

 

下面用一个最简单的Demo,介绍使用如何使用php来调用Memcahce。

一:安装memcache PHP模块

#wget http://pecl.php.net/get/memcache-2.2.4.tgz

# tar zxvf memcache-2.2.4.tgz
# cd memcache-2.2.4

 查找phpize路径

#whereis phpize

 这里是/root/app/php-5.3.3/bin/phpize(一般在php安装路径的bin目录下)

# /root/app/php-5.3.3/bin/phpize
# ./configure --enable-memcache --with-php-config=/root/app/php-5.3.3/bin/php-config
# make
# make install

  在php.ini文件添加一行(/etc目录下)

   extension=memcache.so

  重启httpd

  #service httpd restart

  php里使用phpinfo()看到memcache相关说明信息,才说明memcached扩展安装好。

 

  注:如果仅使用php -m来查看php所加载的扩展,这个并不能表示扩展已经生效。 

 

   注意:

   安装完后可能会有类似这样的提示:

   Installing shared extensions: /usr/local/php/lib/php/extensions/no-debug-non-zts-20050922/ 

   把这个记住,然后修改php.ini,把

   extension_dir = "./" 

   修改为

   extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20050922/"   

   并添加一行

   extension=memcache.so 

 

二:PHP调用memcached

自己写一个PHP程序测试一下

 

    <?php      $memcache = new Memcache; //创建一个memcache对象      $memcache->connect('localhost', 9023) or die ("Could not connect"); //连接Memcached服务器      $memcache->set('key', 'Hello,XiFeiJian'); //设置一个变量到内存中,名称是key 值是test      $get_value = $memcache->get('key'); //从内存中取出key的值      echo $get_value;      ?>  
Copy after login


二:附:memcached常用操作

    <?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();      ?>  
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template