memcache存儲session實現

爲什麼要用memcache來存儲session數據?因爲memcache把數據存在內存裏,讀取速度非常快。

首先要確保服務器已經安裝了memcache,若已經安裝好,查看啓動的memcache服務:

netstat -lp | grep memcached
查看memcache的進程號(根據進程號,可以結束memcache服務:“kill -9 進程號”):

ps -ef | grep memcached
若沒有啓動memcache服務,則可以去過以下命令啓動:

[root@os04 ~]# /usr/local/bin/memcached -d start -u root -m 2120 -p 11211 -c 100000 -f 1.5 -n 300 -P /tmp/memcached.pid
命令執行完成後,可以再重新查看是否啓動服務或者查看進程,上面啓動命令裏面的參數可以根據自己項目的實際需求進行調整。

memcache的環境已經設置並啓動完成後,接下來就要配置php了,要將php的session默認存儲在memcache裏面,只需要配置一下php.ini文件,然後重啓php服務即可。

編輯php.ini

[root@os04 /]# vim /usr/local/php/etc/php.ini
找到session的配置路徑進行設置:



多臺服務器可以用英文逗號隔開,例如:tcp://127.0.0.1:11211,tcp://127.0.0.1:12000

保存php.ini之後,重啓php,如果不知道服務器的內網ip地址,可以通過ifconfig命令查看。


啓動參數說明:

-d 選項是啓動一個守護進程。

-u root 表示啓動memcached的用戶爲root。

-m 是分配給Memcache使用的內存數量,單位是MB,默認64MB。

-M return error on memory exhausted (rather than removing items)。

-u 是運行Memcache的用戶,如果當前爲root 的話,需要使用此參數指定用戶。

-p 是設置Memcache的TCP監聽的端口,最好是1024以上的端口。

-c 選項是最大運行的併發連接數,默認是1024。

-P 是設置保存Memcache的pid文件。

-n 分配給key+value+flags的最小空間(默認:48

-f  塊大小增長因子。(默認:1.25


“-d”參數進一步的解釋

-d install 安裝memcached

-d uninstall 卸載memcached

-d start 啓動memcache服務

-d restart 重啓memcached 服務

-d stop 停止memcached服務

-d shutdown 停止memcached服務


簡單總結下,利用memcache保存session一共有三種方式,上面提到的方式是:

session.save_handler = memcache
session.save_path = "tcp://127.0.0.1:11211"

另外一種是直接在php裏面利用ini_set()來重置:

ini_set('session.save_handler','memcache');
ini_set('session.save_path','tcp://127.0.0.1:11211');

第三種方式同樣也是php程序,直接重寫session的操作處理:

<?php
class MemcacheSession{
    protected $handler = null;
    protected $config  = [
        'host'         => '127.0.0.1', // memcache主機
        'port'         => 11211, // memcache端口
        'expire'       => 3600, // session有效期
        'timeout'      => 0, // 連接超時時間(單位:毫秒)
        'persistent'   => true, // 長連接
        'session_name' => '', // memcache key前綴
    ];

    public function __construct($config = []){
        $this->config = array_merge($this->config, $config);
    }

    /**
     * 打開Session
     * @access public
     * @param string    $savePath
     * @param mixed     $sessName
     */
    public function open($savePath, $sessName){
        // 檢測php環境
        if (!extension_loaded('memcache')) {
            throw new Exception('not support:memcache');
        }
        $this->handler = new \Memcache;
        // 支持集羣
        $hosts = explode(',', $this->config['host']);
        $ports = explode(',', $this->config['port']);
        if (empty($ports[0])) {
            $ports[0] = 11211;
        }
        // 建立連接
        foreach ((array) $hosts as $i => $host) {
            $port = isset($ports[$i]) ? $ports[$i] : $ports[0];
            $this->config['timeout'] > 0 ?
                $this->handler->addServer($host, $port, $this->config['persistent'], 1, $this->config['timeout']) :
                $this->handler->addServer($host, $port, $this->config['persistent'], 1);
        }
        return true;
    }

    /**
     * 關閉Session
     * @access public
     */
    public function close(){
        $this->gc(ini_get('session.gc_maxlifetime'));
        $this->handler->close();
        $this->handler = null;
        return true;
    }

    /**
     * 讀取Session
     * @access public
     * @param string $sessID
     */
    public function read($sessID){
        return (string) $this->handler->get($this->config['session_name'] . $sessID);
    }

    /**
     * 寫入Session
     * @access public
     * @param string    $sessID
     * @param String    $sessData
     * @return bool
     */
    public function write($sessID, $sessData){
        return $this->handler->set($this->config['session_name'] . $sessID, $sessData, 0, $this->config['expire']);
    }

    /**
     * 刪除Session
     * @access public
     * @param string $sessID
     * @return bool
     */
    public function destroy($sessID){
        return $this->handler->delete($this->config['session_name'] . $sessID);
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     * @return true
     */
    public function gc($sessMaxLifeTime){
        return true;
    }
}

//使用
session_set_save_handler(new MemcacheSession([]));
session_start();







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章