Completed
Push — 6.0 ( 95a01d...4b0b4a )
by liu
02:23
created

Redis::push()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 2
b 0
f 0
nc 1
nop 2
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
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
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 */
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...
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
    /**
47
     * 架构函数
48
     * @access public
49
     * @param array $options 缓存参数
50
     */
51
    public function __construct(array $options = [])
52
    {
53
        if (!empty($options)) {
54
            $this->options = array_merge($this->options, $options);
55
        }
56
57
        if (extension_loaded('redis')) {
58
            $this->handler = new \Redis;
59
60
            if ($this->options['persistent']) {
61
                $this->handler->pconnect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout'], 'persistent_id_' . $this->options['select']);
62
            } else {
63
                $this->handler->connect($this->options['host'], (int) $this->options['port'], (int) $this->options['timeout']);
64
            }
65
66
            if ('' != $this->options['password']) {
67
                $this->handler->auth($this->options['password']);
68
            }
69
        } elseif (class_exists('\Predis\Client')) {
70
            $params = [];
71
            foreach ($this->options as $key => $val) {
72
                if (in_array($key, ['aggregate', 'cluster', 'connections', 'exceptions', 'prefix', 'profile', 'replication', 'parameters'])) {
73
                    $params[$key] = $val;
74
                    unset($this->options[$key]);
75
                }
76
            }
77
78
            if ('' == $this->options['password']) {
79
                unset($this->options['password']);
80
            }
81
82
            $this->handler = new \Predis\Client($this->options, $params);
83
84
            $this->options['prefix'] = '';
85
        } else {
86
            throw new \BadFunctionCallException('not support: redis');
87
        }
88
89
        if (0 != $this->options['select']) {
90
            $this->handler->select((int) $this->options['select']);
91
        }
92
    }
93
94
    /**
95
     * 判断缓存
96
     * @access public
97
     * @param string $name 缓存变量名
98
     * @return bool
99
     */
100
    public function has($name): bool
101
    {
102
        return $this->handler->exists($this->getCacheKey($name)) ? true : false;
103
    }
104
105
    /**
106
     * 读取缓存
107
     * @access public
108
     * @param string $name    缓存变量名
109
     * @param mixed  $default 默认值
110
     * @return mixed
111
     */
112
    public function get($name, $default = null)
113
    {
114
        $this->readTimes++;
115
        $key   = $this->getCacheKey($name);
116
        $value = $this->handler->get($key);
117
118
        if (false === $value || is_null($value)) {
119
            return $default;
120
        }
121
122
        return $this->unserialize($value);
123
    }
124
125
    /**
126
     * 写入缓存
127
     * @access public
128
     * @param string            $name   缓存变量名
129
     * @param mixed             $value  存储数据
130
     * @param integer|\DateTime $expire 有效时间(秒)
131
     * @return bool
132
     */
133
    public function set($name, $value, $expire = null): bool
134
    {
135
        $this->writeTimes++;
136
137
        if (is_null($expire)) {
138
            $expire = $this->options['expire'];
139
        }
140
141
        $key    = $this->getCacheKey($name);
142
        $expire = $this->getExpireTime($expire);
143
        $value  = $this->serialize($value);
144
145
        if ($expire) {
146
            $this->handler->setex($key, $expire, $value);
147
        } else {
148
            $this->handler->set($key, $value);
149
        }
150
151
        return true;
152
    }
153
154
    /**
155
     * 自增缓存(针对数值缓存)
156
     * @access public
157
     * @param string $name 缓存变量名
158
     * @param int    $step 步长
159
     * @return false|int
160
     */
161
    public function inc(string $name, int $step = 1)
162
    {
163
        $this->writeTimes++;
164
        $key = $this->getCacheKey($name);
165
166
        return $this->handler->incrby($key, $step);
167
    }
168
169
    /**
170
     * 自减缓存(针对数值缓存)
171
     * @access public
172
     * @param string $name 缓存变量名
173
     * @param int    $step 步长
174
     * @return false|int
175
     */
176
    public function dec(string $name, int $step = 1)
177
    {
178
        $this->writeTimes++;
179
        $key = $this->getCacheKey($name);
180
181
        return $this->handler->decrby($key, $step);
182
    }
183
184
    /**
185
     * 删除缓存
186
     * @access public
187
     * @param string $name 缓存变量名
188
     * @return bool
189
     */
190
    public function delete($name): bool
191
    {
192
        $this->writeTimes++;
193
194
        $key    = $this->getCacheKey($name);
195
        $result = $this->handler->del($key);
196
        return $result > 0;
197
    }
198
199
    /**
200
     * 清除缓存
201
     * @access public
202
     * @return bool
203
     */
204
    public function clear(): bool
205
    {
206
        $this->writeTimes++;
207
        $this->handler->flushDB();
208
        return true;
209
    }
210
211
    /**
212
     * 删除缓存标签
213
     * @access public
214
     * @param array $keys 缓存标识列表
215
     * @return void
216
     */
217
    public function clearTag(array $keys): void
218
    {
219
        // 指定标签清除
220
        $this->handler->del($keys);
221
    }
222
223
    /**
224
     * 追加TagSet数据
225
     * @access public
226
     * @param string $name  缓存标识
227
     * @param mixed  $value 数据
228
     * @return void
229
     */
230
    public function append(string $name, $value): void
231
    {
232
        $key = $this->getCacheKey($name);
233
        $this->handler->sAdd($key, $value);
234
    }
235
236
    /**
237
     * 获取标签包含的缓存标识
238
     * @access public
239
     * @param string $tag 缓存标签
240
     * @return array
241
     */
242
    public function getTagItems(string $tag): array
243
    {
244
        $name = $this->getTagKey($tag);
245
        $key  = $this->getCacheKey($name);
246
        return $this->handler->sMembers($key);
247
    }
248
249
}
250