CodeIgniter实现读写分离
时间: 2024-05-16 17:17:43 浏览: 11
CodeIgniter本身并没有提供读写分离的功能,但是我们可以通过扩展CodeIgniter的数据库类来实现读写分离。
以下是一种简单的实现方式:
1. 在application/core目录下创建MY_DB.php文件,内容如下:
```
class MY_DB extends CI_DB {
protected $_slave_db = NULL;
public function __construct($params = '')
{
parent::__construct($params);
// 连接从数据库
$this->_slave_db = $this->CI->load->database('slave', TRUE);
}
/**
* 执行读操作
*/
public function read($sql, $binds = FALSE, $return_object = TRUE)
{
return $this->_slave_db->query($sql, $binds, $return_object);
}
/**
* 执行写操作
*/
public function write($sql, $binds = FALSE, $return_object = TRUE)
{
return $this->query($sql, $binds, $return_object);
}
}
```
2. 在配置文件中设置主从数据库连接信息,application/config/database.php:
```
// 主数据库
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_master',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
// 从数据库
$db['slave'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'db_slave',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
```
3. 在控制器中使用:
```
class Example extends CI_Controller {
public function index()
{
$this->load->database();
// 执行读操作
$result = $this->db->read("SELECT * FROM `table`");
// 执行写操作
$this->db->write("INSERT INTO `table` (`name`, `age`) VALUES (?, ?)", array('John', 20));
}
}
```
这样,就可以实现简单的读写分离了。当然,实际的应用场景可能更加复杂,需要根据具体的情况进行调整和优化。