cache.redis.func.php
2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* [WeEngine System] Copyright (c) 2014 WE7.CC
* WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
*/
defined('IN_IA') or exit('Access Denied');
function cache_redis() {
global $_W;
static $redisobj;
if (!extension_loaded('redis')) {
return error(1, 'Class Redis is not found');
}
if (empty($redisobj)) {
$config = $_W['config']['setting']['redis'];
$redisobj = new Redis();
try {
if ($config['pconnect']) {
$connect = $redisobj->pconnect($config['server'], $config['port']);
} else {
$connect = $redisobj->connect($config['server'], $config['port']);
}
if (!empty($config['auth'])) {
$auth = $redisobj->auth($config['auth']);
}
} catch (Exception $e) {
return error(-1,'redis连接失败,错误信息:'.$e->getMessage());
}
}
return $redisobj;
}
function cache_read($key) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
if ($redis->exists(cache_prefix($key))) {
$data = $redis->get(cache_prefix($key));
$data = iunserializer($data);
return $data;
}
return '';
}
function cache_search($key) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
$search_keys = $redis->keys(cache_prefix($key) . '*');
$search_data = array();
if (!empty($search_keys)){
foreach ($search_keys as $search_key => $search_value) {
$search_data[$search_value] = iunserializer($redis->get($search_value));
}
}
return $search_data;
}
function cache_write($key, $value, $ttl = CACHE_EXPIRE_LONG) {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
$value = iserializer($value);
if ($redis->set(cache_prefix($key), $value, $ttl)) {
return true;
}
return false;
}
function cache_delete($key){
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
if($redis->delete(cache_prefix($key))) {
unset($GLOBALS['_W']['cache'][$key]);
return true;
}
return false;
}
function cache_clean($key = '') {
$redis = cache_redis();
if (is_error($redis)) {
return $redis;
}
if (!empty($key)) {
if ($keys = $redis->keys(cache_prefix($key) . "*")) {
unset($GLOBALS['_W']['cache']);
return $redis->delete($keys) ? true : false;
}
}
if ($redis->flushAll()) {
unset($GLOBALS['_W']['cache']);
return true;
}
return false;
}
function cache_prefix($key) {
return $GLOBALS['_W']['config']['setting']['authkey'] . $key;
}