memcache简介
memcached是高性能的分布式缓存服务器,用来集中缓存数据库查询结果,减少数据库访问次数,以提高动态Web应用的响应速度
安装软件
yum -y install memcached
# /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
# /usr/lib/systemd/system/memcached.service
[Service]
Type=simple
EnvironmentFile=-/etc/sysconfig/memcached
ExecStart=/usr/bin/memcached -u $USER -p $PORT -m $CACHESIZE -c $MAXCONN $OPTIONS
[Install]
WantedBy=multi-user.target
systemctl enable --now memcached
telnet测试memcached
# memcached常用指令
add name 0 180 10 # 变量不存在则添加,0为是否压缩,180为在内存中存在时间,10为值的长度(telnet中需要)
set name 0 180 10
replace name 0 180 10 # 替换
get name # 读取变量
delete name # 删除变量
flush_all # 清空所有
php+memcached
安装php的memcached扩展
yum -y install php-pecl-memcache
# rpm -ql php-pecl-memcache
systemctl restart php-fpm
编写PHP页面
# /usr/local/nginx/html/test.php
<?php
$memcache=new Memcache;
$memcache->connect('localhost',11211) or die('could not connect!!');
$memcache->set('key','test');
$get_vaules=$memcache->get('key');
echo $get_vaules;
?>
实现Session共享
# 修改配置文件
# vim /etc/php-fpm.d/www.conf
# 修改前
php_value[session.save_handler]=files
php_value[session.save_path]=/var/lib/php/session
# 修改后
php_value[session.save_handler]=memcache
php_value[session.save_path]="tcp://192.168.92.100:11211"
# 重启服务
systemctl restart php-fpm