Completed
Push — 6.0 ( d6c8d7...cb8a0b )
by liu
05:58
created

Redis   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 219
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 68
c 2
b 0
f 0
dl 0
loc 219
ccs 0
cts 67
cp 0
rs 10
wmc 24

11 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 40 10
A set() 0 19 3
A delete() 0 6 1
A inc() 0 7 1
A getTagItems() 0 3 1
A dec() 0 7 1
A push() 0 3 1
A clearTag() 0 4 1
A clear() 0 6 1
A has() 0 3 1
A get() 0 11 3
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
6
// +----------------------------------------------------------------------
7
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
8
// +----------------------------------------------------------------------
9
// | Author: liu21st <[email protected]>
10
// +----------------------------------------------------------------------
11
12
namespace think\cache\driver;
13
14
use think\cache\Driver;
15
16
/**
17
 * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
18
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
19
 *
20
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
21
 * @author    尘缘 <[email protected]>
22
 */
23
class Redis extends Driver
24
{
25
    /**
26
     * 配置参数
27
     * @var array
28
     */
29
    protected $options = [
30
        'host'       => '127.0.0.1',
31
        'port'       => 6379,
32
        'password'   => '',
33
        'select'     => 0,
34
        'timeout'    => 0,
35
        'expire'     => 0,
36
        'persistent' => false,
37
        'prefix'     => '',
38
        'tag_prefix' => 'tag:',
39
        'serialize'  => [],
40
    ];
41
42
    /**
43
     * 架构函数
44
     * @access public
45
     * @param  array $options 缓存参数
46
     */
47
    public function __construct(array $options = [])
48
    {
49
        if (!empty($options)) {
50
            $this->options = array_merge($this->options, $options);
51
        }
52
53
        if (extension_loaded('redis')) {
54
            $this->handler = new \Redis;
55
56
            if ($this->options['persistent']) {
57
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
58
            } else {
59
                $this->handler->connect($this->options['host'], (int) $this->options['port'], $this->options['timeout']);
60
            }
61
62
            if ('' != $this->options['password']) {
63
                $this->handler->auth($this->options['password']);
64
            }
65
        } elseif (class_exists('\Predis\Client')) {
66
            $params = [];
67
            foreach ($this->options as $key => $val) {
68
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
69
                    $params[$key] = $val;
70
                    unset($this->options[$key]);
71
                }
72
            }
73
74
            if ('' == $this->options['password']) {
75
                unset($this->options['password']);
76
            }
77
78
            $this->handler = new \Predis\Client($this->options, $params);
0 ignored issues
show
Bug introduced by
The type Predis\Client was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
79
80
            $this->options['prefix'] = '';
81
        } else {
82
            throw new \BadFunctionCallException('not support: redis');
83
        }
84
85
        if (0 != $this->options['select']) {
86
            $this->handler->select($this->options['select']);
87
        }
88
    }
89
90
    /**
91
     * 判断缓存
92
     * @access public
93
     * @param  string $name 缓存变量名
94
     * @return bool
95
     */
96
    public function has($name): bool
97
    {
98
        return $this->handler->exists($this->getCacheKey($name));
99
    }
100
101
    /**
102
     * 读取缓存
103
     * @access public
104
     * @param  string $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
105
     * @param  mixed  $default 默认值
106
     * @return mixed
107
     */
108
    public function get($name, $default = false)
109
    {
110
        $this->readTimes++;
111
112
        $value = $this->handler->get($this->getCacheKey($name));
113
114
        if (is_null($value) || false === $value) {
115
            return $default;
116
        }
117
118
        return $this->unserialize($value);
119
    }
120
121
    /**
122
     * 写入缓存
123
     * @access public
124
     * @param  string            $name 缓存变量名
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
125
     * @param  mixed             $value  存储数据
126
     * @param  integer|\DateTime $expire  有效时间(秒)
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after parameter name; 2 found
Loading history...
127
     * @return bool
128
     */
129
    public function set($name, $value, $expire = null): bool
130
    {
131
        $this->writeTimes++;
132
133
        if (is_null($expire)) {
134
            $expire = $this->options['expire'];
135
        }
136
137
        $key    = $this->getCacheKey($name);
138
        $expire = $this->getExpireTime($expire);
139
        $value  = $this->serialize($value);
140
141
        if ($expire) {
142
            $this->handler->setex($key, $expire, $value);
143
        } else {
144
            $this->handler->set($key, $value);
145
        }
146
147
        return true;
148
    }
149
150
    /**
151
     * 自增缓存(针对数值缓存)
152
     * @access public
153
     * @param  string $name 缓存变量名
154
     * @param  int    $step 步长
155
     * @return false|int
156
     */
157
    public function inc(string $name, int $step = 1)
158
    {
159
        $this->writeTimes++;
160
161
        $key = $this->getCacheKey($name);
162
163
        return $this->handler->incrby($key, $step);
164
    }
165
166
    /**
167
     * 自减缓存(针对数值缓存)
168
     * @access public
169
     * @param  string $name 缓存变量名
170
     * @param  int    $step 步长
171
     * @return false|int
172
     */
173
    public function dec(string $name, int $step = 1)
174
    {
175
        $this->writeTimes++;
176
177
        $key = $this->getCacheKey($name);
178
179
        return $this->handler->decrby($key, $step);
180
    }
181
182
    /**
183
     * 删除缓存
184
     * @access public
185
     * @param  string $name 缓存变量名
186
     * @return bool
187
     */
188
    public function delete($name): bool
189
    {
190
        $this->writeTimes++;
191
192
        $this->handler->del($this->getCacheKey($name));
193
        return true;
194
    }
195
196
    /**
197
     * 清除缓存
198
     * @access public
199
     * @return bool
200
     */
201
    public function clear(): bool
202
    {
203
        $this->writeTimes++;
204
205
        $this->handler->flushDB();
206
        return true;
207
    }
208
209
    /**
210
     * 删除缓存标签
211
     * @access public
212
     * @param  array  $keys 缓存标识列表
213
     * @return void
214
     */
215
    public function clearTag(array $keys): void
216
    {
217
        // 指定标签清除
218
        $this->handler->del($keys);
219
    }
220
221
    /**
222
     * 追加(数组)缓存数据
223
     * @access public
224
     * @param  string $name 缓存标识
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
225
     * @param  mixed  $value 数据
226
     * @return void
227
     */
228
    public function push(string $name, $value): void
229
    {
230
        $this->handler->sAdd($name, $value);
231
    }
232
233
    /**
234
     * 获取标签包含的缓存标识
235
     * @access public
236
     * @param  string $tag 缓存标签
237
     * @return array
238
     */
239
    public function getTagItems(string $tag): array
240
    {
241
        return $this->handler->sMembers($tag);
242
    }
243
244
}
245