workerman的優(yōu)點(diǎn)中有一條“數(shù)據(jù)或者資源可以全局共享”,請問怎么實(shí)現(xiàn)?我想在Event.php中用mysql_connect()創(chuàng)建一個(gè)數(shù)據(jù)連接$db_conn,然后后面有新的連接進(jìn)來時(shí),可以不用再次連接,如何做?是否用一個(gè)在Event 或者Gateway class中聲明一個(gè)static $db_conn = null,然后做一個(gè)初始化就行了?
可以寫一個(gè)數(shù)據(jù)庫的類,然后使用單例模式,類似下面這樣
class DB
{
static $dbConn = null;
public static function instance()
{
if(!self::$dbConn)
{
self::$dbConn = new PDO(xxxx);
}
}
}
數(shù)據(jù)庫資源全局共享時(shí)有一點(diǎn)需要注意,當(dāng)這個(gè)共享的數(shù)據(jù)庫鏈接長時(shí)間沒有任何操作時(shí)可能會被mysql服務(wù)端關(guān)閉鏈接,被mysql服務(wù)端關(guān)閉鏈接后的數(shù)據(jù)庫資源再次被使用的時(shí)候會報(bào)mysql gone away 錯(cuò)誤,使用時(shí)如果遇到這種錯(cuò)誤(錯(cuò)誤碼為2006)重連即可