CakePHP --- Load Balancing and MySQL Master and Slaves

本文介绍如何在CakePHP中实现MySQL主从复制进行负载均衡。通过简单配置即可完成读写分离,提高应用程序性能。文章提供具体配置示例及控制器中更新操作的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://bakery.cakephp.org/articles/eagerterrier/2007/05/26/load-balancing-and-mysql-master-and-slaves-2


If you are currently using MySql master/slave replication for load balancing and wish to transport to cakePHP, it really couldn't be easier.
2 simple steps to master/slave replication in cake..

Firstly in app/config/database.php write the following:-


class DATABASE_CONFIG { 
        var $default = array( 
                'driver'                => 'mysql', 
                'host'                  => 'slave.host.ip', 
                'login'                 => '....', 
                'password'              => '.....', 
                'database'              => 'my_db' 
        ); 

        var $master = array( 
                'driver'                => 'mysql', 
                'host'                  => 'master.host.ip', 
                'login'                 => '....', 
                'password'              => '.....', 
                'database'              => 'my_db' 
        ); 



Then, in app/app_model.php, create 4 new methods:


function beforeSave() { 
    $this->useDbConfig = 'master'; 
    return true;


function afterSave() { 
    $this->useDbConfig = 'default'; 
    return true;


function beforeDelete() { 
    $this->useDbConfig = 'master'; 
     return true;


function afterDelete() { 
    $this->useDbConfig = 'default'; 
     return true;


It really is as simple as that.

However, there are some instance where you may want to use a query in your controller where you update/insert information. In this case, use the following:


$this->ModelName->setDataSource('master');
$this->ModelName->query("UPDATE post_views SET views=views+1 WHERE id=1234");
$this->ModelName->setDataSource('default');

I use this where I want information to be updated, but don't want cake to flush the cache. But then again, that may be like crossing the streams in Ghostbusters, so don't listen to me..



With thanks to Nate and gwoo


http://www.howtoforge.com/mysql_master_master_replication


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值