Passed
Pull Request — 6.0 (#2648)
by
unknown
12:18
created

Redis::has()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 6
rs 10
1
<?php
2
// +----------------------------------------------------------------------
3
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
4
// +----------------------------------------------------------------------
5
// | Copyright (c) 2006~2021 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
declare (strict_types = 1);
12
13
namespace think\cache\driver;
14
15
use think\cache\Driver;
16
17
/**
18
 * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
19
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
20
 *
21
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
22
 * @author    尘缘 <[email protected]>
23
 */
24
class Redis extends Driver
25
{
26
    /** @var \Predis\Client|\Redis */
27
    protected $handler;
28
29
    /**
30
     * 配置参数
31
     * @var array
32
     */
33
    protected $options = [
34
        'host'       => '127.0.0.1',
35
        'port'       => 6379,
36
        'password'   => '',
37
        'select'     => 0,
38
        'timeout'    => 0,
39
        'expire'     => 0,
40
        'persistent' => false,
41
        'prefix'     => '',
42
        'tag_prefix' => 'tag:',
43
        'serialize'  => [],
44
    ];
45
46
    /**<?php
47
// +----------------------------------------------------------------------
48
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
49
// +----------------------------------------------------------------------
50
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved.
51
// +----------------------------------------------------------------------
52
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
53
// +----------------------------------------------------------------------
54
// | Author: liu21st <[email protected]>
55
// +----------------------------------------------------------------------
56
declare (strict_types = 1);
57
58
namespace think\cache\driver;
59
60
use think\cache\Driver;
61
62
/**
63
 * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
64
 * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
65
 *
66
 * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
67
 * @author    尘缘 <[email protected]>
68
 */
69
class Redis extends Driver
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_CLASS, expecting T_FUNCTION or T_CONST on line 69 at column 0
Loading history...
70
{
71
    /** @var \Predis\Client|\Redis */
72
    protected $handler;
73
74
    /**
75
     * 配置参数
76
     * @var array
77
     */
78
    protected $options = [
79
        'host'       => '127.0.0.1',
80
        'port'       => 6379,
81
        'password'   => '',
82
        'select'     => 0,
83
        'timeout'    => 0,
84
        'expire'     => 0,
85
        'persistent' => false,
86
        'prefix'     => '',
87
        'tag_prefix' => 'tag:',
88
        'serialize'  => [],
89
    ];
90
91
    /**
92
     * 架构函数
93
     * @access public
94
     * @param array $options 缓存参数
95
     */
96
    public function __construct(array $options = [])
97
    {
98
        if (!empty($options)) {
99
            $this->options = array_merge($this->options, $options);
100
        }
101
102
        if (extension_loaded('redis')) {
103
            $this->handler = new \Redis;
104
105
            if ($this->options['persistent']) {
106
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
107
            } else {
108
                $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
109
            }
110
111
            if ('' != $this->options['password']) {
112
                $this->handler->auth($this->options['password']);
113
            }
114
        } elseif (class_exists('\Predis\Client')) {
115
            $params = [];
116
            foreach ($this->options as $key => $val) {
117
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
118
                    $params[$key] = $val;
119
                    unset($this->options[$key]);
120
                }
121
            }
122
123
            if ('' == $this->options['password']) {
124
                unset($this->options['password']);
125
            }
126
127
            $this->handler = new \Predis\Client($this->options, $params);
128
129
            $this->options['prefix'] = '';
130
        } else {
131
            throw new \BadFunctionCallException('not support: redis');
132
        }
133
134
        if (0 != $this->options['select']) {
135
            $this->handler->select((int) $this->options['select']);
136
        }
137
    }
138
139
    /**
140
     * 判断缓存
141
     * @access public
142
     * @param string $name 缓存变量名
143
     * @return bool
144
     */
145
    public function has($name): bool
146
    {
147
        return $this->handler->exists($this->getCacheKey($name)) ? true : false;
148
    }
149
150
    /**
151
     * 读取缓存
152
     * @access public
153
     * @param string $name    缓存变量名
154
     * @param mixed  $default 默认值
155
     * @return mixed
156
     */
157
    public function get($name, $default = null)
158
    {
159
        $this->readTimes++;
160
        $key   = $this->getCacheKey($name);
161
        $value = $this->handler->get($key);
162
163
        if (false === $value || is_null($value)) {
164
            return $default;
165
        }
166
167
        return $this->unserialize($value);
168
    }
169
    /**
170
     * 模糊查询
171
     * @access public
172
     * @param string $name    缓存变量名
173
     * @return mixed
174
     */
175
    public function keys($name)
176
    {
177
        $this->readTimes++;
178
        $value = $this->handler->keys($name);
179
180
        if (false === $value || is_null($value)) {
181
            return null;
182
        }
183
        return  $value;
184
    }
185
186
    /**
187
     * 写入缓存
188
     * @access public
189
     * @param string            $name   缓存变量名
190
     * @param mixed             $value  存储数据
191
     * @param integer|\DateTime $expire 有效时间(秒)
192
     * @return bool
193
     */
194
    public function set($name, $value, $expire = null): bool
195
    {
196
        $this->writeTimes++;
197
198
        if (is_null($expire)) {
199
            $expire = $this->options['expire'];
200
        }
201
202
        $key    = $this->getCacheKey($name);
203
        $expire = $this->getExpireTime($expire);
204
        $value  = $this->serialize($value);
205
206
        if ($expire) {
207
            $this->handler->setex($key, $expire, $value);
208
        } else {
209
            $this->handler->set($key, $value);
210
        }
211
212
        return true;
213
    }
214
215
    /**
216
     * 自增缓存(针对数值缓存)
217
     * @access public
218
     * @param string $name 缓存变量名
219
     * @param int    $step 步长
220
     * @return false|int
221
     */
222
    public function inc(string $name, int $step = 1)
223
    {
224
        $this->writeTimes++;
225
        $key = $this->getCacheKey($name);
226
227
        return $this->handler->incrby($key, $step);
228
    }
229
230
    /**
231
     * 自减缓存(针对数值缓存)
232
     * @access public
233
     * @param string $name 缓存变量名
234
     * @param int    $step 步长
235
     * @return false|int
236
     */
237
    public function dec(string $name, int $step = 1)
238
    {
239
        $this->writeTimes++;
240
        $key = $this->getCacheKey($name);
241
242
        return $this->handler->decrby($key, $step);
243
    }
244
245
    /**
246
     * 删除缓存
247
     * @access public
248
     * @param string $name 缓存变量名
249
     * @return bool
250
     */
251
    public function delete($name): bool
252
    {
253
        $this->writeTimes++;
254
255
        $key    = $this->getCacheKey($name);
256
        $result = $this->handler->del($key);
257
        return $result > 0;
258
    }
259
260
    /**
261
     * 清除缓存
262
     * @access public
263
     * @return bool
264
     */
265
    public function clear(): bool
266
    {
267
        $this->writeTimes++;
268
        $this->handler->flushDB();
269
        return true;
270
    }
271
272
    /**
273
     * 删除缓存标签
274
     * @access public
275
     * @param array $keys 缓存标识列表
276
     * @return void
277
     */
278
    public function clearTag(array $keys): void
279
    {
280
        // 指定标签清除
281
        $this->handler->del($keys);
282
    }
283
284
    /**
285
     * 追加TagSet数据
286
     * @access public
287
     * @param string $name  缓存标识
288
     * @param mixed  $value 数据
289
     * @return void
290
     */
291
    public function append(string $name, $value): void
292
    {
293
        $key = $this->getCacheKey($name);
294
        $this->handler->sAdd($key, $value);
295
    }
296
297
    /**
298
     * 获取标签包含的缓存标识
299
     * @access public
300
     * @param string $tag 缓存标签
301
     * @return array
302
     */
303
    public function getTagItems(string $tag): array
304
    {
305
        $name = $this->getTagKey($tag);
306
        $key  = $this->getCacheKey($name);
307
        return $this->handler->sMembers($key);
308
    }
309
310
}
311
312
     * 架构函数
313
     * @access public
314
     * @param array $options 缓存参数
315
     */
316
    public function __construct(array $options = [])
317
    {
318
        if (!empty($options)) {
319
            $this->options = array_merge($this->options, $options);
320
        }
321
322
        if (extension_loaded('redis')) {
323
            $this->handler = new \Redis;
324
325
            if ($this->options['persistent']) {
326
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
327
            } else {
328
                $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
329
            }
330
331
            if ('' != $this->options['password']) {
332
                $this->handler->auth($this->options['password']);
333
            }
334
        } elseif (class_exists('\Predis\Client')) {
335
            $params = [];
336
            foreach ($this->options as $key => $val) {
337
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
338
                    $params[$key] = $val;
339
                    unset($this->options[$key]);
340
                }
341
            }
342
343
            if ('' == $this->options['password']) {
344
                unset($this->options['password']);
345
            }
346
347
            $this->handler = new \Predis\Client($this->options, $params);
348
349
            $this->options['prefix'] = '';
350
        } else {
351
            throw new \BadFunctionCallException('not support: redis');
352
        }
353
354
        if (0 != $this->options['select']) {
355
            $this->handler->select((int) $this->options['select']);
356
        }
357
    }
358
359
    /**
360
     * 判断缓存
361
     * @access public
362
     * @param string $name 缓存变量名
363
     * @return bool
364
     */
365
    public function has($name): bool
366
    {
367
        return $this->handler->exists($this->getCacheKey($name)) ? true : false;
368
    }
369
370
    /**
371
     * 读取缓存
372
     * @access public
373
     * @param string $name    缓存变量名
374
     * @param mixed  $default 默认值
375
     * @return mixed
376
     */
377
    public function get($name, $default = null)
378
    {
379
        $this->readTimes++;
380
        $key   = $this->getCacheKey($name);
381
        $value = $this->handler->get($key);
382
383
        if (false === $value || is_null($value)) {
384
            return $default;
385
        }
386
387
        return $this->unserialize($value);
388
    }
389
390
    /**
391
     * 写入缓存
392
     * @access public
393
     * @param string            $name   缓存变量名
394
     * @param mixed             $value  存储数据
395
     * @param integer|\DateTime $expire 有效时间(秒)
396
     * @return bool
397
     */
398
    public function set($name, $value, $expire = null): bool
399
    {
400
        $this->writeTimes++;
401
402
        if (is_null($expire)) {
403
            $expire = $this->options['expire'];
404
        }
405
406
        $key    = $this->getCacheKey($name);
407
        $expire = $this->getExpireTime($expire);
408
        $value  = $this->serialize($value);
409
410
        if ($expire) {
411
            $this->handler->setex($key, $expire, $value);
412
        } else {
413
            $this->handler->set($key, $value);
414
        }
415
416
        return true;
417
    }
418
419
    /**
420
     * 自增缓存(针对数值缓存)
421
     * @access public
422
     * @param string $name 缓存变量名
423
     * @param int    $step 步长
424
     * @return false|int
425
     */
426
    public function inc(string $name, int $step = 1)
427
    {
428
        $this->writeTimes++;
429
        $key = $this->getCacheKey($name);
430
431
        return $this->handler->incrby($key, $step);
432
    }
433
434
    /**
435
     * 自减缓存(针对数值缓存)
436
     * @access public
437
     * @param string $name 缓存变量名
438
     * @param int    $step 步长
439
     * @return false|int
440
     */
441
    public function dec(string $name, int $step = 1)
442
    {
443
        $this->writeTimes++;
444
        $key = $this->getCacheKey($name);
445
446
        return $this->handler->decrby($key, $step);
447
    }
448
449
    /**
450
     * 删除缓存
451
     * @access public
452
     * @param string $name 缓存变量名
453
     * @return bool
454
     */
455
    public function delete($name): bool
456
    {
457
        $this->writeTimes++;
458
459
        $key    = $this->getCacheKey($name);
460
        $result = $this->handler->del($key);
461
        return $result > 0;
462
    }
463
464
    /**
465
     * 清除缓存
466
     * @access public
467
     * @return bool
468
     */
469
    public function clear(): bool
470
    {
471
        $this->writeTimes++;
472
        $this->handler->flushDB();
473
        return true;
474
    }
475
476
    /**
477
     * 删除缓存标签
478
     * @access public
479
     * @param array $keys 缓存标识列表
480
     * @return void
481
     */
482
    public function clearTag(array $keys): void
483
    {
484
        // 指定标签清除
485
        $this->handler->del($keys);
486
    }
487
488
    /**
489
     * 追加TagSet数据
490
     * @access public
491
     * @param string $name  缓存标识
492
     * @param mixed  $value 数据
493
     * @return void
494
     */
495
    public function append(string $name, $value): void
496
    {
497
        $key = $this->getCacheKey($name);
498
        $this->handler->sAdd($key, $value);
499
    }
500
501
    /**
502
     * 获取标签包含的缓存标识
503
     * @access public
504
     * @param string $tag 缓存标签
505
     * @return array
506
     */
507
    public function getTagItems(string $tag): array
508
    {
509
        $name = $this->getTagKey($tag);
510
        $key  = $this->getCacheKey($name);
511
        return $this->handler->sMembers($key);
512
    }
513
514
}
515