[PHP7] 利用Memcached 儲存 Session

URL Link //n.sfs.tw/11138

2017-05-25 01:38:36 By 張○○

PHP7安裝memcached,提升網頁速度

OS

CentOS Linux release 7.3.1611 (Core)

PHP 7.0.18 (cli) (built: Apr 15 2017 07:09:11) ( NTS )

安裝

# yum install epel-release

# yum install memcached

# yum install php70w-pecl-memcached

完裝完畢後會多一個檔案:

/etc/php.d/z-memcached.ini

設定

vi /etc/sysconfig/memcached

PORT="11211"
USER="memcached"
MAXCONN="3000"
CACHESIZE="200"
OPTIONS="-l 127.0.0.1"

第3行最大連線數;

第4行記憶體大小,單位是mb

第5行限定監聽介面,若留空就全部介面

# vi /etc/php.ini

session.save_handler = memcached
session.save_path = "127.0.0.1:11211"

啟動

# systemctl start memcached

# systemctl restart httpd

檢查php模組
# php -m | grep memcached
memcached <一片空白代表你沒裝好>

查看Memcached狀態

物件清單
# memcached-tool 127.0.0.1:11211

# memcached-tool 127.0.0.1:11211 display

統計資料
# memcached-tool 127.0.0.1:11211 stats

物件內容
# memcached-tool 127.0.0.1:11211 dump

其他

1. 設定開機啟動

systemctl enable memcached

2. PHP的session原本存在 /var/lib/php/session/ 改成 memcached後就不會再存於此

3. 重啟 apache不會清除資料,但重啟memcached會。

4. Codeigniter3 在PHP7使用memcached會遇到問題,目前尚無法解決(只能關掉錯誤)

$ vi application/config/config.php

$config['sess_driver'] = 'memcached';  //files
$config['sess_save_path'] = '127.0.0.1:11211'; //NULL;

A PHP Error was encountered

Severity: Warning

Message: Memcached::touch(): using touch command with binary protocol is not recommended with libmemcached versions below 1.0.18, please use ascii protocol or upgrade libmemcached

Filename: drivers/Session_memcached_driver.php

參考資料

[1] https://ssorc.tw/5965

[2] https://www.cyberciti.biz/faq/rhel-fedora-linux-install-memcached-caching-system-rpm/

[3] http://php.net/manual/en/memcached.sessions.php#99646

[4] https://blog.longwin.com.tw/2010/04/use-memcached-store-php-session-2010/