mysql 缓存某张表_用mysql建一张表来模拟memcache做缓存操作类,要求用到工厂模式,单件模式,适配器模式...

本文通过创建一个名为`mysql_cache_demo`的MySQL表,来模拟Memcache的键值对存储。利用工厂模式、单例模式和适配器模式,实现了一个类库,提供了类似Memcache的`set`、`get`、`delete`方法。此外,还展示了如何在PHP中创建`Cache`类、`CacheInterface`接口、以及针对不同缓存系统的子类如`CacheApc`、`CacheMemcache`和`CacheMySQL`。文章旨在探讨将MySQL作为缓存系统的一种实践,尽管这不是最佳方案,但作为学习设计模式和缓存系统的练习非常有价值。

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

具体要求:建一张表,字段可以有key,value,cachetime,ctime封装一个把mysql当作kvdb的类来操作这个表,像memcache一样,有set,get,delete方法等。要求用到工厂模式,单件模式,适配器模式。

我建的表:

CREATE TABLE IF NOT EXISTS `mysql_cache_demo` (

`cache_key` varchar(255) NOT NULL,

`cache_value` text NOT NULL,

`cache_time` int(11) NOT NULL COMMENT '缓存时间',

`create_time` int(11) NOT NULL COMMENT '创建时间',

`update_time` int(11) NOT NULL COMMENT '更新时间',

PRIMARY KEY (`cache_key`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

当然只是一个练习吧,Mysql做缓存系统肯定不是什么好办法,代码呢也测试通过都(代码贴上来排版全乱了,就酱紫吧,能大概看下就行了):

class Cache

{

private static $instance = array();

/**

* 缓存实例化的工厂方法并且确保单例

*/

public static function getInstance( $type,$options=array()){

$type = strtolower(trim($type));

if(isset(self::$instance[$type])){

return self::$instance[$type];

}

$class = 'Cache'.ucwords($type);

//class_exists 前提是已经有了自动载入机制

if(class_exists($class)){

$cache = new $class($options);

self::$instance[$type] = $cache;

}else{

throw new Exception('error cache type');

}

return $cache;

}

}

/**

* 封装适配器接口规范

*/

interface CacheInterface

{

function set($name, $value, $expire = null);

function get($name);

function delete($name);

}

abstract class CacheAbstract implements CacheInterface

{

//设置默认的

public $options = array('prefix'=>'zmk_','expire'=>'60');

}

class CacheApc extends CacheAbstract

{

public function __construct($options=array()) {

if(!function_exists('apc_cache_info')) {

die('apc缓存扩展不存在');

}

$this->options = array_merge($this->options,$options);

}

public function get($name) {

return apc_fetch($this->options['prefix'].$name);

}

public function set($name, $value, $expire = null) {

if(is_null($expire)) {

$expire = $this->options['expire'];

}

$name = $this->options['prefix'].$name;

return apc_store($name, $value, $expire);

}

public function delete($name) {

return apc_delete($this->options['prefix'].$name);

}

public function clear() {

return apc_clear_cache();

}

}

$apc = Cache::getInstance('Cache',array('prefix'=>'zhoumengkang_'));

$apc->set('test','周梦康',60);

echo $apc->get('test');

var_dump($apc->options);

class CacheMemcache extends CacheAbstract

{

private $handler;

public function __construct($options=array()) {

if(!extension_loaded('memcache')){

die('memcache扩展不存在');

}

$this->options = array_merge($this->options,array('host'=>'localhost','port'=>'11211'),$options);

$this->handler = new Memcache;

$func = $options['persistent'] ? 'pconnect' : 'connect';

if($options['timeout'] === false){

$this->handler->$func($this->options['host'], $this->options['port']);

}else{

$this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);

}

}

public function get($name) {

return $this->handler->get($this->options['prefix'].$name);

}

public function set($name, $value, $expire = null) {

if(is_null($expire)) {

$expire = $this->options['expire'];

}

return $this->handler->set($this->options['prefix'].$name, $value, $expire);

}

public function delete($name,$timeout = null) {

if(is_null($timeout)){

return $this->handler->delete($this->options['prefix'].$name);

}else{

return $this->handler->delete($this->options['prefix'].$name,$timeout);

}

}

public function clear() {

return $this->handler->flush();

}

}

//$memcache = new CacheMemcache(array('prefix'=>'haha_','persistent'=>true,'timeout'=>false));

$memcache = Cache::getInstance('memcache',array('prefix'=>'haha_','persistent'=>true,'timeout'=>false));

$memcache->set('test2','周梦康康梦周',60);

echo $memcache->get('test2');

class CacheMySQL extends CacheAbstract

{

private $handler;

public function __construct($options=array()) {

if(!extension_loaded('pdo_mysql')){

die('pdo_mysql扩展不存在');

}

$this->options = array_merge($this->options,array('host'=>'localhost','port'=>'3306'),$options);

$this->handler = new PDO('mysql:host='.$this->options['host'].';port='.$this->options['port'].';dbname='.$this->options['database'], $this->options['user'], $this->options['password']);

$this->handler->query("set names utf8");

}

public function get($name) {

$name = $this->options['prefix'].$name;

$sql = "SELECT `cache_value` FROM `{$this->options['tablename']}` WHERE `cache_key` = '{$name}'";

$res = $this->handler->query($sql);

foreach ($res as $row) {

return $row['cache_value'];

}

}

public function set($name, $value, $expire = null) {

if(is_null($expire)) {

$expire = $this->options['expire'];

}

$name = $this->options['prefix'].$name;

$time = time();

$expire = $expire + time();//假设定时任务每秒请求执行一次autoDeleteCachePerSecond()

if($this->handler->query("SELECT * FROM `{$this->options['tablename']}` WHERE `cache_key` = '{$name}'")){

$sql = "UPDATE `{$this->options['tablename']}` SET `cache_value` = '{$value}',`update_time` = {$time} ,`cache_time` = {$expire}";

}else{

$sql = "INSERT INTO `{$this->options['tablename']}` (`cache_key`,`cache_value`,`create_time`,`cache_time`) VALUES('{$name}','{$value}',{$time},{$expire})";

}

return $this->handler->exec($sql);

}

/**

* 每秒自动全表扫描删除该存活期等于该时间戳下的所有缓存数据

*/

public function autoDeleteCachePerSecond() {

$sql = "DELETE FROM `{$this->options['tablename']}` WHERE `cache_time` = ".time();

$this->handler->exec($sql);

}

public function delete($name) {

$sql = "DELETE FROM `{$this->options['tablename']}` WHERE `cache_key` = '".$this->options['prefix'].$name."'";

$this->handler->exec($sql);

}

public function clear() {

$sql = "DELETE FROM `{$this->options['tablename']}`";

$this->handler->exec($sql);

}

}

//$mysqlCache = new CacheMySQL(array('database'=>'design_patterns','tablename'=>'mysql_cache_demo','user'=>'root','password'=>'zmkzmk'));

$mysqlCache = Cache::getInstance('Mysql',array('database'=>'design_patterns','tablename'=>'mysql_cache_demo','user'=>'root','password'=>'zmkzmk'));

$mysqlCache->set('mengkang','php_mysql_cache_test');

echo $mysqlCache->get('mengkang');

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值