CodeIgniter实现读写分离
时间: 2024-05-04 08:22:37 浏览: 12
CodeIgniter支持读写分离,可以通过配置多个数据库连接实现。
首先,在 `application/config/database.php` 文件中配置主库和从库的连接信息,例如:
```php
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydatabase',
'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' => 'readonly',
'password' => '',
'database' => 'mydatabase',
'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['default']` 表示主库连接,`$db['slave']` 表示从库连接。
然后,在 CodeIgniter 中使用从库查询时,需要手动切换数据库连接,例如:
```php
// 获取从库连接对象
$slave_db = $this->load->database('slave', TRUE);
// 查询从库数据
$query = $slave_db->get('mytable');
```
需要注意的是,从库只能进行读操作,不能进行写操作。如果需要进行写操作,需要切换回主库连接。例如:
```php
// 获取主库连接对象
$master_db = $this->load->database('default', TRUE);
// 插入数据到主库
$data = array('name' => 'John', 'email' => 'john@example.com');
$master_db->insert('mytable', $data);
```
需要在应用程序中根据实际情况选择使用主库或从库连接进行读写操作。