<?php
class
redisCache {
private
$host
;
private
$port
;
private
$lifetime
;
private
$cacheid
;
private
$data
;
public
$redis
;
function
__construct(
$lifetime
=1800) {
$this
->host =
"127.0.0.1"
;
$this
->port =
"6379"
;
$redis
=
new
Redis();
$redis
->pconnect(
$this
->host,
$this
->port);
$this
->redis=
$redis
;
$this
->cacheid =
$this
->getcacheid();
$this
->lifetime =
$lifetime
;
$this
->data=
$redis
->hMGet(
$this
->cacheid,
array
('content','creattime'));
}
private
function
isvalid(){
$data
=
$this
->data;
if
(!
$data
['content'])
return
false;
if
(time() -
$data
['creattime'] >
$this
->lifetime)
return
false;
return
true;
}
public
function
write(
$mode
=0,
$content
='') {
switch
(
$mode
) {
case
0:
$content
= ob_get_contents();
break
;
default
:
break
;
}
ob_end_flush();
try
{
$this
->redis->hMset(
$this
->cacheid,
array
('content'=>
$content
,'creattime'=>time()));
$this
->redis->expireAt(
$this
->cacheid, time() +
$this
->lifetime);
}
catch
(Exception
$e
) {
$this
->error('写入缓存失败!');
}
}
public
function
load() {
if
(
$this
->isvalid()) {
echo
$this
->data['content'];
exit
();
}
else
{
ob_start();
}
}
public
function
clean() {
try
{
$this
->redis->hDel(
$this
->cacheid,
array
('content','creattime'));
}
catch
(Exception
$e
) {
$this
->error('清除缓存失败!');
}
}
private
function
getcacheid() {
return
$this
->dir.md5(
$this
->geturl()).
$this
->ext;
}
private
function
geturl() {
$url
= '';
if
(isset(
$_SERVER
['REQUEST_URI'])) {
$url
=
$_SERVER
['REQUEST_URI'];
}
else
{
$url
=
$_SERVER
['Php_SELF'];
$url
.=
empty
(
$_SERVER
['QUERY_STRING'])?'':'?'.
$_SERVER
['QUERY_STRING'];
}
return
$url
;
}
private
function
error(
$str
) {
echo
'<p style=
"color:red;"
>'.
$str
.'</p>';
}
}
?>