悠悠楠杉
网站页面
Cache.class.php
<?php
class Mysql
{
public $link;
public function __construct()
{
$this->conn();
}
/**
* 连接数据库,从配置文件读取配置信息
*/
public function conn()
{
$cfg = require 'config.php';
$this->link = new mysqli($cfg['host'], $cfg['name'], $cfg['password'], $cfg['databaseName'], $cfg['port']);
$this->query('set names ' . $cfg['charset']);
}
/**
* 发送query查询
* @param string $sql sql语句
* @return mixed
*/
public function query($sql)
{
return $this->link->query($sql);
}
/**
* 查询多行数据
* @param string $sql sql语句
* @return array
*/
public function getAll($sql)
{
$res = $this->query($sql);
$data = [];
while ($row = $res->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
}
class Cache
{
public $m;
public function __construct()
{
//创建实例
//Redis
$this->m = new Redis();
$this->m->connect('127.0.0.1', 6379);
$this->m->auth('password');//Redis密码,设置、修改密码后需要重载配置
//Memcached
/*$this->m = new Memcached();
$this->m->addServer('127.0.0.1', 11211);*/
//Memcache
/*$this->m = new Memcache();
$this->m->connect('127.0.0.1', 11211);*/
}
/**
* 添加
* @param string $key 用于存储值的键名
* @param string $value 存储的值
* @param int $time 过期时间,单位:秒
* @return boolean
*/
public function memAdd($key, $value, $time = 3600)
{
return $this->m->set($key, $value, $time);
}
/**
* 获取
* @param string $key 要检索的元素的key
* @return string 失败返回false
*/
public function memGet($key)
{
return $this->m->get($key);
}
/**
* 删除
* @param string $key 要删除的元素的key
* @return bool 失败返回false
*/
public function del($key)
{
return $this->m->delete($key);
}
/**
* 清空
* @return bool 失败返回false
*/
public function clear()
{
return $this->m->flushDB();
}
/**
* 获取使用序列化来存储数据
* @param string $key 可以是md5加密后的sql语句
* @param string $sql sql语句
* @return array
*/
public function selectMsg($key, $sql)
{
//先查询数据缓存是否有该数据
$msg = $this->memGet($key);
//没有则查询数据库
// var_dump($msg);
if (!$msg) {
echo '跑数据库';
$mysql = new Mysql();
$list = $mysql->getAll($sql);
//var_dump($list);
//把查询出来的结果序列化存进memcached中
$data = serialize($list);
$this->memAdd($key, $data);
//返回数据库查找的值
return $list;
} else {
echo '不跑数据库';
//有则反序列输出
return unserialize($msg);
}
}
}
//调用
$cache = new Cache();
$sql = 'select * from art';
$key = md5($sql);
$list = $cache->selectMsg($key,$sql);
var_dump($list);
//更新数据
$cache->memAdd($key,null);
//删除数据
$cache->del($key);
//清空数据
$cache->clear();
config.php
<?php
return array(
'host' => 'localhost',
'name' => 'cs',
'password' => '123456',
'databaseName' => 'cs',
'port' => '3306',
'charset' => 'utf8'
);