php 守护进程怎么维持数据库的长连接

63 篇文章 0 订阅
14 篇文章 0 订阅

什么是守护进程?
守护进程是在后台底层运行的进程,不和前端发生交互,只在某个特定的时段需要去完成的部分工作的进程。

问题1:当守护进程运行的时候,因工作任务量大,计算运行耗时长,但mysql有最大连接时间,超过这个时间后mysql数据库就自动断连,怎么维持数据库的链接呢?

解决办法:在每一次sql语句执行之前先判定当前数据库连接是否是一个有效的数据库连接。如果是一个有效的连接,则继续执行后续的工作内容,如果不是一个有效连接(因超时,或其它原因导致的这个连接对象已不能正常使用),则重新初始化一个连接,丢弃以前的连接

怎么去实现呢?
我这里做了一个demo 欢迎大家参考
核心控制库文件 MyPDO.php

<?php
/**
 * MyPDO
 * @author Jason.Wei <jasonwei06@hotmail.com>
 * @license http://www.sunbloger.com/
 * @version 5.0 utf8
 */
class MyPDO
{
    private $config,$dbh,$initNum=0,$initTime;

    public function __construct($config)
    {
        $this->setConfig($config);

        $this->dbInit();
    }

    /**
     * 构造
     * 
     * @return MyPDO
     */
    private function dbInit()
    {
        $config = $this->getConfig();

        if(empty($config))
            throw new Exception('not get database config',10001);

        try{
            $dsn        = 'mysql:host='.$config['dbHost'].';dbname='.$config['dbName'];
            $dbUser     = $config['dbUser'];
            $dbPasswd   = $config['dbPwd'];
            $dbCharset  = $config['dbCharset'];
            $this->dbh  = new PDO($dsn, $dbUser, $dbPasswd);
            $this->dbh->exec('SET character_set_connection='.$dbCharset.', character_set_results='.$dbCharset.', character_set_client=binary');

            $this->initTime = time();
        } catch (PDOException $e) {
            $this->outputError($e->getMessage());
        }
    }
    
    /**
     * 防止克隆
     * 
     */
    private function __clone() {}
    
    /**
     * Query 查询 多行
     *
     * @param String $strSql SQL语句
     * @param String $queryMode 查询方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    public function query($strSql, $keyVal = array(),$queryMode = 'all')
    {
        $this->clientDb();

        $recordset = $this->dbh->prepare($strSql);
		
		if(!empty($keyVal))
		{
			$recordset->execute($keyVal);
		}else{
			$recordset->execute();
		}
		

        if ($recordset) {
			
            $recordset->setFetchMode(PDO::FETCH_ASSOC);
			
            $result = $recordset->fetchAll();
 
        } else {
            $result = null;
        }
        return $result;
    }
	
	 /**
     * Query 查询 单行数据
     *
     * @param String $strSql SQL语句
     * @param String $queryMode 查询方式(All or Row)
     * @param Boolean $debug
     * @return Array
     */
    public function fetch($strSql, $keyVal = array())
    {
        $this->clientDb();

        $recordset = $this->dbh->prepare($strSql);
		
		if(!empty($keyVal))
		{
			$recordset->execute($keyVal);
		}else{
			$recordset->execute();
		}
		
        if ($recordset) {
            $recordset->setFetchMode(PDO::FETCH_ASSOC);

            $result = $recordset->fetch();
        } else {
            $result = null;
        }
        return $result;
    }
    
    /**
     * Update 更新
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function update($table, $arrayDataValue, $where = '')
    {
        $this->clientDb();

        if ($where) {
            $strSql = '';
			
            foreach ($arrayDataValue as $key => $value)
			{
                $strSql .= ", `$key`='$value'";
            }
			
            $strSql = substr($strSql, 1);
			
            $strSql = "UPDATE `$table` SET $strSql WHERE $where";
        } else {
            $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        }
		
        $result = $this->dbh->exec($strSql);
		
        return $result;
    }
    
    /**
     * Insert 插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function insert($table, $arrayDataValue)
    {
        $this->clientDb();

        $this->checkFields($table, $arrayDataValue);
		
        $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
       
		$result = $this->dbh->exec($strSql);
        
        return $result;
    }
    
    /**
     * Replace 覆盖方式插入
     *
     * @param String $table 表名
     * @param Array $arrayDataValue 字段与值
     * @param Boolean $debug
     * @return Int
     */
    public function replace($table, $arrayDataValue)
    {
        $this->clientDb();

        $this->checkFields($table, $arrayDataValue);
        $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
        $result = $this->dbh->exec($strSql);
        return $result;
    }
    
    /**
     * Delete 删除
     *
     * @param String $table 表名
     * @param String $where 条件
     * @param Boolean $debug
     * @return Int
     */
    public function delete($table, $where = '')
    {
        $this->clientDb();

        if ($where == '') {
            $this->outputError("'WHERE' is Null");
        } else {
            $strSql = "DELETE FROM `$table` WHERE $where";
            $result = $this->dbh->exec($strSql);
            return $result;
        }
    }
    
    /**
     * execSql 执行SQL语句
     *
     * @param String $strSql
     * @param Boolean $debug
     * @return Int
     */
    public function execSql($strSql)
    {
        $this->clientDb();

        $result = $this->dbh->exec($strSql);
        return $result;
    }
    
    /**
     * 获取字段最大值
     * 
     * @param string $table 表名
     * @param string $field_name 字段名
     * @param string $where 条件
     */
    public function getMaxValue($table, $field_name, $where = '')
    {
        $this->clientDb();

        $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
		
		$recode = $this->dbh->query($strSql);
		$recode->setFetchMode(PDO::FETCH_ASSOC);
		$arrTemp = $recode->fetch();
		
        $maxValue = $arrTemp["MAX_VALUE"];
        if ($maxValue == "" || $maxValue == null) {
            $maxValue = 0;
        }
        return $maxValue;
    }
    
    /**
     * 获取指定列的数量
     * 
     * @param string $table
     * @param string $field_name
     * @param string $where
     * @param bool $debug
     * @return int
     */
    public function getCount($table, $field_name, $where = '')
    {
        $this->clientDb();

        $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
        if ($where != '') $strSql .= " WHERE $where";
        $recode = $this->dbh->query($strSql);
		$recode->setFetchMode(PDO::FETCH_ASSOC);
		$arrTemp = $recode->fetch();
		return $arrTemp['NUM'];
    }
    
    /**
     * 获取表引擎
     * 
     * @param String $dbName 库名
     * @param String $tableName 表名
     * @param Boolean $debug
     * @return String
     */
    public function getTableEngine($dbName, $tableName)
    {
        $this->clientDb();

        $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";
		
		$recode = $this->dbh->query($strSql);
		$recode->setFetchMode(PDO::FETCH_ASSOC);
		$arrayTableInfo = $recode->fetch();
		
        //$arrayTableInfo = $this->query($strSql);
        return $arrayTableInfo[0]['Engine'];
    }
    
    /**
     * beginTransaction 事务开始
     */
    public function beginTransaction()
    {
        $this->dbh->beginTransaction();
    }
    
    /**
     * commit 事务提交
     */
    public function commit()
    {
        $this->dbh->commit();
    }
    
    /**
     * rollback 事务回滚
     */
    public function rollback()
    {
        $this->dbh->rollback();
    }
    
    /**
     * transaction 通过事务处理多条SQL语句
     * 调用前需通过getTableEngine判断表引擎是否支持事务
     *
     * @param array $arraySql
     * @return Boolean
     */
    public function execTransaction($arraySql)
    {
        $this->clientDb();

        $retval = 1;
		
        $this->beginTransaction();
		
        foreach ($arraySql as $strSql)
		{
            if ($this->execSql($strSql) == 0) $retval = 0;
        }
        if ($retval == 0)
		{
            $this->rollback();
			
            return false;
        } else {
            $this->commit();
            return true;
        }
    }

    /**
     * checkFields 检查指定字段是否在指定数据表中存在
     *
     * @param String $table
     * @param array $arrayField
     */
    private function checkFields($table, $arrayFields)
    {
        $this->clientDb();

        $fields = $this->getFields($table);
        foreach ($arrayFields as $key => $value) {
            if (!in_array($key, $fields)) {
                $this->outputError("Unknown column `$key` in field list.");
            }
        }
    }
    
    /**
     * getFields 获取指定数据表中的全部字段名
     *
     * @param String $table 表名
     * @return array
     */
    private function getFields($table)
    {
        $this->clientDb();

        $fields = array();
        $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
        $recordset->setFetchMode(PDO::FETCH_ASSOC);
        $result = $recordset->fetchAll();
        foreach ($result as $rows) {
            $fields[] = $rows['Field'];
        }
        return $fields;
    }

    /**
     * 数据库监听
     */
    private function clientDb()
    {
        try{
            $time = time();
            if($time - $this->initTime >= $this->config['overtime'])
                throw new Exception('client time error',10003);

            $result = null;
            $sql = "select * from {$this->config['client_table']} where 1";
            $recordset = $this->dbh->prepare($sql);
            $recordset->execute();

            if ($recordset) {
                $recordset->setFetchMode(PDO::FETCH_ASSOC);
                $result = $recordset->fetch();
            }
            if(empty($result))
                throw new Exception('not db',10002);
        }catch(Exception $e)
        {
            if($e->getCode() == 10002)
            {
                $this->destruct();

                $this->initNum++;

                $pdoErrCode = $this->dbh->errorCode();
                $pdoErrInfo = $this->dbh->errorInfo();
                echo "mysql init : {$this->initNum} error code : " . $pdoErrCode . " info : " . $pdoErrInfo . "\n";
                $this->dbInit();
            }else if($e->getCode() == 10003){
                $this->initNum++;
                echo "mysql auto init : {$this->initNum}\n";
                $this->destruct();
                $this->dbInit();
            }else{
                throw new Exception('error ' . $e->getCode());
            }
        }finally {

        }
    }


    /**
     * getPDOError 捕获PDO错误信息
     */
    private function getPDOError()
    {
        if ($this->dbh->errorCode() != '00000') {
            $arrayError = $this->dbh->errorInfo();
            $this->outputError($arrayError[2]);
        }
    }
    
    /**
     * 输出错误信息
     * 
     * @param String $strErrMsg
     */
    private function outputError($strErrMsg)
    {
        throw new Exception('MySQL Error: '.$strErrMsg);
    }
    
    /**
     * destruct 关闭数据库连接
     */
    public function destruct()
    {
        $this->dbh = null;
    }

    /**
     * @return mixed
     */
    public function getConfig()
    {
        return $this->config;
    }

    /**
     * @param mixed $config
     */
    public function setConfig($config)
    {
        $this->config = $config;
    }
}
?>

配置文件 config.php

<?php
return [
    'db'    =>  [
        'dbUser'	=>	'root',	//数据用户名
        'dbPwd'		=>	'123456', //数据密码
        'dbHost'	=>	'localhost',	//数据库连接地址
        'dbName'	=>	'test',	//数据库名称
        'dbCharset'	=>	'utf8',	//字符校对
        'overtime'  =>  50,		//超时自动重连,当前数据库连接使用超过50s后自动重新连接一次数据,不受必须抛出异常的控制
        'client_table'=>'client_console'  //检测表
    ]
];

执行 main.php

<?php

//结束php 超时时间限制
set_time_limit(0);

//载入配置
$config = require ('config.php');

//mysql 初始化
require ('./pdo.class.php');
$db = new MyPDO($config['db']);

//打开输出缓冲控制
ob_start();

$sql = "update client_info set num=num+1 where id=1";

for($i=0;$i<10000000;$i++)
{
    $db->execSql($sql);

    //等待时间 1 秒
    sleep(1);

    echo "execute : " . $i . " \n";

    //输出缓冲内容
    echo ob_get_clean();    //获取当前缓冲区内容并清除当前的输出缓冲
    flush();   //刷新缓冲区的内容,输出
}

测试表两张表的结构
table:client_console
在这里插入图片描述

tanle:client_info
在这里插入图片描述

关于配置中$config[‘client_table’]的作用
每一次在执行sql语句之前,数据连接对象都会去查询这张表的内容,原因:如果能正常查询出来内容,说明当前数据库连接对象是一个可用的连接对象,否则则是一个不可用的数据库连接对象。根据此得出的结果去判定是否需要初始化数据库连接。

问题2:当超时重新连接数据库后,数据库会保留上一次的连接记录吗?

不会保存,超时过后,数据库就自动释放了,php pdo释放数据库连接很简单,直接赋值为null就行了,不会产生数据库连接过多而导致数据库性能变低的情况。实测情况如下图
在这里插入图片描述
可以通过命令“SHOW FULL processlist” 来查看当前数据库与所有服务器之间产生了多少个连接,注意是“所有”,只要和当前数据库产生了连接交互,都能通过此命令显示出来。
从上图可以看到有两个连接,未标红的是管理工具产生的一个连接,已标红的是php产生的数据库连接。这里我着重看php产生的数据库连接,从图中可以看到php产生的数据库连接id为235。当程序运行一段时间后,再次检查,结果如下图
在这里插入图片描述

可以看到,数据库连接还是两个,一个是我的管理工具,一个是php守护进程产生的连接,但目前php守护进程产生的连接id和之前的截图不一样,区别是目前的id为240。这是怎么回事呢?因为在我打字的这段时间,我的守护进程重新初始化了5次数据库连接(这个id的值是由mysql分配的,我们不用去管)。结合程序的运行,我们就能得出每一次当我赋予pdo连接对象为空值的时候,php与mysql之间的连接就已经断开了。

在我的案例中,为了稳定维持数据库的长连接,我做了两层机制。
1、第一层,当前mysql连接对象运行50s后(超时参数值在config中设置),mysql数据库连接对象自动初始化重连

2、第二层,在每一次执行sql之前,先判定当前mysql连接对象是否有效,无效的话自动初始化重连。
这两步的实现都是在底层实现,我们不用管,我们还是平时一样的使用操作对象就好了。

学如逆海行舟,不仅则退,希望谭老师的博客能对你有所助益。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值