CI架構3.0關於session的redis,資料庫的使用方法

來源:互聯網
上載者:User

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連線逾時時間

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.