3.0變動是比較大的,session支援了redis,memcache,files,database。檔案的就不說了,這個是最簡單的。這裡說一下使用資料庫、redis來儲存session的方法。
首選,因為其手冊沒有更新,手冊講的是2.0版本的使用方法。3.0已經不是這樣使用。這裡使用資料庫的方式,最大的變化是資料庫變了。
| 代碼如下 |
複製代碼 |
CREATE TABLE IF NOT EXISTS `ci_sessions` ( `id` varchar(40) NOT NULL, `ip_address` varchar(45) NOT NULL, `timestamp` int(10) unsigned DEFAULT 0 NOT NULL, `data` blob NOT NULL, PRIMARY KEY (id), KEY `ci_sessions_timestamp` (`timestamp`) ); |
請使用這個建資料庫,應該根據其配置說明應該就會使用資料庫的儲存方式了。
當然如果你重構了他的資料庫操作類,尤其是增加了自動主從讀寫分離等,那麼你需要也重構這個session_database.php了,這個有問題可以交流,也很簡單。ci的好處就可以很方便重構。
2、使用redis
這個我是看他代碼才知道怎麼用的。
看下這個檔案。Session_redis_driver.php
| 代碼如下 |
複製代碼 |
public function __construct(&$params) { parent::__construct($params); if (empty($this->_config['save_path'])) { log_message('error', 'Session: No Redis save path configured.'); } elseif (preg_match('#(?:tcp://)?([^:?]+)(?:\:(\d+))?(\?.+)?#', $this->_config['save_path'], $matches)) { isset($matches[3]) OR $matches[3] = ''; // Just to avoid undefined index notices below $this->_config['save_path'] = array( 'host' => $matches[1], 'port' => empty($matches[2]) ? NULL : $matches[2], 'password' => preg_match('#auth=([^\s&]+)#', $matches[3], $match) ? $match[1] : NULL, 'database' => preg_match('#database=(\d+)#', $matches[3], $match) ? (int) $match[1] : NULL, 'timeout' => preg_match('#timeout=(\d+\.\d+)#', $matches[3], $match) ? (float) $match[1] : NULL ); preg_match('#prefix=([^\s&]+)#', $matches[3], $match) && $this->_key_prefix = $match[1]; } else { log_message('error', 'Session: Invalid Redis save path format: '.$this->_config['save_path']); } if ($this->_config['match_ip'] === TRUE) { $this->_key_prefix .= $_SERVER['REMOTE_ADDR'].':'; } } |
根據這個建構函式,我們發現,redis的串連資訊全在save_path這個配置項。所以我們可以這樣配置
| 代碼如下 |
複製代碼 |
| $config['sess_save_path'] = '127.0.0.1:6379?auth=admin&prefix=ci_sess:&database=2&timeout=60'; |
這個地方,你根據代碼就可以看出來,ip,連接埠。然後是後面的password就是匹配的auth=之後,後面就很簡單了。prefix是session儲存的首碼,database是庫號,redis是分庫的。timeout連線逾時時間