基于YIi2的mysql,mongo分库和断线重连

    使用的是的Yii2的多模块版,此为生产环境稳定运行版本

    配置文件main.php中

'components' => [
    //mysql分库
    'db_fenku' => [
        'class' => 'common\components\db\MysqlConnection',
        'dbname' => 'fenku',
        'charset' => 'utf8',
    ],
    //mongo分库
    'mongo_femku' => [
        'class' => 'common\components\db\MongoConnection',
        'dbname' => 'fenku',
    ],
]

一.mysql部分

    文件\common\components\db\MysqlConnection.php,为mysql分库的基类

<?php
namespace common\components\db;

use Yii;

class MysqlConnection extends \yii\db\Connection{
    
    public $dbname;
    
    protected $config = array();    //连接属性

    public function __construct($config=[]){
        // ... 配置生效前的初始化过程
        //配置参数的传递参数类型
        //mysql的配置参数
        //$host = ……
        //$port = ……
        //$this->dbname = ……

        $this->config['dsn'] = "mysql:host={$host};port={$port};dbname={$this->dbname}";
//        $this->config['username'] = ……
//        $this->config['password'] = ……

        //附加配置
        $this->config['charset'] = $config['charset']??'utf8';
        if(isset($config['tablePrefix'])){
            $this->config['tablePrefix'] = $config['tablePrefix'];
        }
        //实例化数据库连接类
        parent::__construct($this->config);
    }
    
    /*
     * 检查连接是否有效,失效则重连.只适用于长期执行不释放的脚本
     * 连接超过3600秒强制重连
     */
    public $ping_time;
    public function checkPing(){
        if(!$this->pdo){return true;}    //属性pdo*不*存在则说明尚未执行连接
        $nowtime = time();
        if(!$this->ping_time){$this->ping_time = $nowtime;}
        $duration = $nowtime - $this->ping_time;
        if($duration>3600){   //超过时间强制重连
            $this ->reconnect();
        }else{
            try{
                $res = $this -> pdo -> getAttribute(\PDO::ATTR_SERVER_INFO);
//                echo json_encode($res),PHP_EOL;
                return $res;
            }catch (\PDOException $e) {
                $this ->reconnect();
            }
        }
    }
    
    /*
     * 强制重连
     */
    public function reconnect(){
        parent::__construct($this->config);
        $this->ping_time = time();
    }
    
    /*
     * 获取库名
     */
    public function dbName(){
        return $this->dbname;
    }

}

    文件\common\models\fenku\CommonDb.php为mysql表模型的继承类

<?php
namespace common\models\core;
use Yii;
use yii\db\ActiveRecord;

abstract class CommonDb extends ActiveRecord{
    
    const DB = 'db_fenku';

    public static $MyDbConnect;
            
    function __construct($config = array()){

        if($config){    //此处条件根据实际设定

        }else{
            $config['db'] = self::DB;
            self::$MyDbConnect= new \common\components\db\MysqlConnection($config);
        }
        
        parent::__construct();
    }

    public static function getDb(){
        if(self::$MyDbConnect){
            
        }else{
            $db = self::DB;
            self::$MyDbConnect = \Yii::$app->$db;
        }
        return self::$MyDbConnect;
    }
    
    public function dbName(){
        return self::getDb() -> dbname;
    }

}

    文件\common\models\fenku\Test.php为表模型使用示例

<?php
namespace common\models\fenku;

class Test extends CommonDb{

}

二.mongo部分

    文件\common\components\db\MongoConnection.php为mongo分库基类

<?php
namespace common\components\db;

use Yii;

class MongoConnection extends \yii\mongodb\Connection{
    
    public $dbname;
    
    protected $config = array();    //连接属性

    public function __construct($config=[]){
        
        // ... 配置生效前的初始化过程
        //配置参数的传递参数类型
        //mongo的配置参数
        //$host = ……
        //$port = ……
        //$this->dbname = ……
        //$this->config['username'] = ……
        //$this->config['password'] = ……
        

        if(empty($this->config['username'])||empty($this->config['password'])){
            $this->config['dsn'] = "mongodb://{$host}:{$port}/{$this->dbname}";
        }else{
            $this->config['dsn'] = "mongodb://{$this->config['username']}:{$this->config['password']}@{$host}:{$port}";
            $this -> setDefaultDatabaseName($this->dbname);     //设置默认数据库,这步骤很重要!
        }
        //实例化数据库连接类
        parent::__construct($this->config);
    }
    
    /*
     * 检查连接是否有效,失效则重连.只适用于长期执行不释放的脚本
     * 连接超过3600秒强制重连
     */
    public $ping_time;
    public function checkPing(){
        $nowtime = time();
        if(!$this->ping_time){$this->ping_time = $nowtime;}
        $duration = $nowtime - $this->ping_time;
        if($duration>3600){   //超过时间强制重连
            $this ->reconnect();
        }else{
            try{
                $res = $this -> createCommand('db');
//                echo json_encode($res),PHP_EOL;
                return $res;
            }catch (\PDOException $e) {
                $this ->reconnect();
            }
        }
    }
    
    /*
     * 强制重连
     */
    public function reconnect(){
        parent::__construct($this->config);
        $this->ping_time = time();
    }
    
    /*
     * 获取库名
     */
    public function dbName(){
        return $this->dbname;
    }

}

    文件\common\models\mongoFenku\CommonDb.php为mongo表模型的继承类

<?php
namespace common\models\mongoCore;

use yii\mongodb\ActiveRecord;

abstract class CommonDb extends ActiveRecord{
    
    const DB = 'mongo_fenku';

    public static $MyDbConnect;
            
    function __construct($config = array()){
            if($config){    //此处条件根据实际设定
                
            }else{
                $config['db'] = self::DB;
                self::$MyDbConnect= new \common\components\db\MongoConnection($config);
        }
        parent::__construct();
    }

    public static function getDb(){
        if(self::$MyDbConnect){
            
        }else{
            $db = self::DB;
            self::$MyDbConnect = \Yii::$app->$db;
        }
        return self::$MyDbConnect;
    }
    
    public function dbName(){
        return self::getDb() -> dbname;
    }

}

    文件\common\models\mongoFenku\test.php为表模型示例

<?php
namespace common\models\mongoFenku;

class Test extends CommonDb{

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值