文章目录

一、memcached前端数据缓存

1.测试lnmp环境。

[root@lnmp nginx]# netstat -lntup|egrep "nginx|php|mysql"
tcp        0      0 0.0.0.0:80                  0.0.0.0:*                   LISTEN      1401/nginx
tcp        0      0 127.0.0.1:9000              0.0.0.0:*                   LISTEN      1503/php-fpm
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      1232/mysqld
[root@lnmp nginx]# cat /application/nginx/html/www/index.php
<?php
        $link_id=mysql_connect('localhost','root','000000') or mysql_error();
        if($link_id){
                echo "mysql successful by https://blog.csdn.net/liang_operations!";
        }else{
                echo mysql_error();
        }
?>
[root@Memcached ~]# curl http://10.0.0.130
mysql successful by https://blog.csdn.net/liang_operations!

2.下载安装memcache

[root@lnmp ~]# wget http://pecl.php.net/get/memcache-3.0.8.tgz
[root@lnmp ~]# tar xf memcache-3.0.8.tgz
[root@lnmp ~]# cd memcache-3.0.8
[root@lnmp memcache-3.0.8]# /application/php/bin/phpize
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626
[root@lnmp memcache-3.0.8]# ./configure --enable-memcache --with-php-config=/application/php/bin/php-config --with-zlib-dir
[root@lnmp memcache-3.0.8]# make && make install
[root@lnmp memcache-3.0.8]# ll /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/memcache.so
-rwxr-xr-x. 1 root root 449093 Oct  7 10:54 /usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/memcache.so

3.修改php.ini配置文件

[root@lnmp memcache-3.0.8]# vi /application/php/lib/php.ini
extension_dir = "/usr/local/php/lib/php/extensions/no-debug-non-zts-20090626/"
extensio = memcache.so###增加

4.重启nginx与php

[root@lnmp memcache-3.0.8]# pkill php-fpm
[root@lnmp memcache-3.0.8]# php-fpm
[root@lnmp memcache-3.0.8]# nginx -s reload

5.编写php连接memcached测试

[root@Memcached ~]# netstat -lntup|grep mem
tcp        0      0 0.0.0.0:11212               0.0.0.0:*                   LISTEN      10035/memcached
tcp        0      0 :::11212                    :::*                        LISTEN      10035/memcached
[root@lnmp memcache-3.0.8]# cat /application/nginx/html/www/index.php
<?php
$memcache = new Memcache;             //创建一个memcache对象
$memcache->connect('10.0.0.139', 11211) or die ("Could not connect"); //连接Memcached服务器
$memcache->set('key', 'test');        //设置一个变量到内存中,名称是key 值是test
$get_value = $memcache->get('key');   //从内存中取出key的值
echo $get_value;
?>
[root@lnmp ~]# curl http://10.0.0.130/index.php
test

二、memcached解决web会话保持

1.修改配置文件(所有web环境)

默认/application/php/lib/php.ini配置
session.save_handler = files ###以什么形式存,默认是文件。
;session.save_path = "/tmp"  ###存放的位置
修改/application/php/lib/php.ini
session.save_handler = memcache
session.save_path = "tcp://10.0.0.139:11212"
提示:
10.0.0.139:11212 为memcached数据库缓存的IP及端口

2.重启

[root@lnmp ~]# pkill php-fpm
[root@lnmp ~]# php-fpm
10-07 16:02