-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedisCounter.php
58 lines (49 loc) · 1.36 KB
/
RedisCounter.php
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
<?php
/**
* redis计数器工具类,可用于解决并发操作
* Class RedisCounter
*/
class RedisCounter
{
private $config = [];
private $redis = null;
public function __construct($config)
{
$this->config = $config;
$this->redis = $this->connect();
}
public function incr($key, $incr=1)
{
return intval($this->redis->incrBy($key, $incr));
}
public function expire($key, $time)
{
return $this->redis->expire($key, $time);
}
public function get($key)
{
return intval($this->redis->get($key));
}
public function delete($key)
{
$this->redis->delete($key);
}
private function connect()
{
try{
$redis = new Redis();
$redis->connect($this->config['host'], $this->config['port'], $this->config['timeout'], $this->config['reserved'], $this->config['retry_interval']);
//是否密码验证
if (!empty($this->config['auth'])){
$redis->auth($this->config['auth']);
}
//选择哪个数据库,默认是0
if (!empty($this->config['index'])){
$redis->select($this->config['index']);
}
}catch (RedisException $exception){
throw new Exception($exception->getMessage());
}
return $redis;
}
}