当前位置:Gxlcms > PHP教程 > php装载memcache模块的示例代码详解(图)

php装载memcache模块的示例代码详解(图)

时间:2021-07-01 10:21:17 帮助过:47人阅读

memcache

定义

memcache是一套分布式的高速缓存系统
目前被许多网站使用以提升网站的访问速度,尤其对于一些大型的

工作流程

1.先检查客户端访问的数据是否在于memcache,如果有就直接返回
2.如果不在memcache,就去查数据库,同时缓存一份到memcache,大大提高读取速度。

应用和特性

1.用来做网页或数据库高速缓存
2.可用来做session共享
3.适用于数据变动小但多(如微博粉丝+1)
4.存储在内存,不能数据持久化

缓存优化规则:28原则

20%:热数据,经常被访问的数据。用作缓存,存于内存
80%:基本不变化的数据,存于固态硬盘

php装载memcache模块

检测当前php环境

  1. vim ~/.bash_profile
  2. PATH=$PATH:$HOME/bin:/usr/local/lnmp/mysql/bin/:/usr/local/lnmp/php/bin

. ~/.bash_profile 或者做软链接

  1. [root@server11 bin]# ln -s /usr/local/lnmp/php/bin /usr/local/bin/

编译

  1. tar zxf memcache-2.2.5.tgz cd memcache-2.2.5
  2. phpize 准备预编译环境

1287.png

./configure make && make install

保证php的执行路径是源码包的路径

  1. [root@server11 memcache-2.2.5]# which php /usr/local/lnmp/php/bin/php
  2. cd /usr/local/lnmp/php/etc/
  3. vim php.ini 记住是.
  4. 863 extension=memcache.so
  5. /etc/init.d/php-fpm start

检验

  1. [root@server11 etc]# php -m |grep memcache

1288.png

rpm -qa |grep php 保证没有rpm包干扰

后台安装配置

  1. yum install memcached -y
  2. /etc/init.d/memcached start

监听端口 netstat -antlpue

  1. udp
  2. 0
  3. 0 0.0.0.0:11211
  4. 0.0.0.0:*
  5. 498
  6. 10940
  7. 3706/memcached

访问memcached数据库

  1. yum install telnet -y
  2. telnet localhost 11211
  1. set name 0 0 6
  2. westos
  3. STORED
  4. get name
  5. VALUE name 0 6
  6. westos
  7. END
  8. delete name
  9. DELETED
  10. get name
  11. END

编写监控页面

cd memcache-2.2.5

cp memcache.php /usr/local/nginx/html/

vim memcache.php

  1. 23 define('ADMIN_PASSWORD','westos'); // Admin Password
  2. 28 $MEMCACHE_SERVERS[] = ''; // add more as an array
  3. 29 $MEMCACHE_SERVERS[] = 'mymemcache-server2:11211'; // add more as an arra y

编写测试页面

vim test.php

  1. <?php
  2. $memcache = new Memcache;
  3. $memcache->connect('127.0.0.1', 11211) or die ("Could not connect");
  4. $version = $memcache->getVersion();
  5. echo "Server's version: ".$version."\n";
  6. $tmp_object = new stdClass;
  7. $tmp_object->str_attr = 'test';
  8. $tmp_object->int_attr = 123;
  9. $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the
  10. server");
  11. echo "Store data in the cache (data will expire in 10 seconds)\n";
  12. $get_result = $memcache->get('key');
  13. echo "Data from the cache:\n";
  14. var_dump($get_result);
  15. ?>

启动nginx

nginx

检验

在浏览器访问:

1. 172.25.88.11/memcache.php 监控cache命中率

2. 172.25.88.11/test.php

不断刷新,可以在监控页面看到,缓存的命中率(Hits)越来越大

1289.png

1290.png

以上就是php装载memcache模块的示例代码详解(图)的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行