当前位置:Gxlcms > mysql > 基于mysql的仿memcache缓存类

基于mysql的仿memcache缓存类

时间:2021-07-01 10:21:17 帮助过:54人阅读

当年在sae的时候,内置的mysql类用得挺舒服的。后来自己简单封装了下,runSql方法执行的sql语句,getData方法取得结果数组,Transactions方法实现事务。 mysql = new FaMysql(); } function set($key,$value,$expire = 31536000){//默认有效期一年 $now = ti

当年在sae的时候,内置的mysql类用得挺舒服的。后来自己简单封装了下,runSql方法执行的sql语句,getData方法取得结果数组,Transactions方法实现事务。 mysql = mysql_connect($options['host'],$options['username'],$options['password']) or die ("Database connection error."); mysql_select_db($options['database'],$this->mysql); mysql_query("set names '" . $options['charset'] . "'"); } public function Transactions(array $sql){ mysql_query("BEGIN"); $r = 1; foreach($sql as $key => $row) { $res = mysql_query($row); if(!$res) {$r = 0;} } if(!$r){mysql_query("ROLLBACK");}else{mysql_query("COMMIT");} mysql_query("END"); } public function runSql($sql){ mysql_query($sql) or die(mysql_error()); } public function getData($sql){ $result = mysql_query($sql) or die(mysql_error()); $array = array(); while($row = mysql_fetch_assoc($result)) { $array[] = $row; } return $array; } } 刚开始没买vps,RP主机又不提供memcache缓存,所以自己实现的这么个玩意。set方法存储数据,get方法获取数据,del方法删除数据,都只支持string哦。 class FaMemcache{ private $mysql; private $TABLENAME = 'memcache'; public function __construct(){ $this->mysql = new FaMysql(); } function set($key,$value,$expire = 31536000){//默认有效期一年 $now = time(); $valid = $now + $expire; $data = $this->mysql->getData("SELECT Fa_key FROM `$this->TABLENAME` WHERE Fa_key = '$key'"); if(count($data)!=0){ $this->mysql->runsql("UPDATE `$this->TABLENAME` SET Fa_value = '$value',Valid = '$valid' WHERE Fa_key = '$key'"); }else{ $this->mysql->runsql("INSERT INTO `$this->TABLENAME` (Fa_key,Fa_value,Valid) VALUES ('$key','$value','$valid')"); } } function get($key){ $now = time(); $data = $this->mysql->getData("SELECT Fa_value FROM `$this->TABLENAME` WHERE Fa_key = '$key' AND $now > Valid"); if(count($data)!=0){ return $data[0]['Fa_value']; }else{ return null; } } function del($key){ $this->mysql->runsql("DELETE FROM `$this->TABLENAME` WHERE Fa_key = '$key'"); } }

人气教程排行