-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedisCounter.php
More file actions
109 lines (101 loc) · 2.46 KB
/
RedisCounter.php
File metadata and controls
109 lines (101 loc) · 2.46 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
<?php
/**
* php 基于Redis实现计数器类
*
* @author fdipzone
* @DateTime 2023-03-27 21:49:29
*
* Description:
* php基于Redis实现自增计数,主要使用redis的incr方法,并发执行时保证计数自增唯一。
*
* Func:
* public incr 执行自增计数并获取自增后的数值
* public get 获取当前计数
* public reset 重置计数
* private connect 创建redis连接
*/
class RedisCounter{
/**
* redis连接配置
*
* @var array
*/
private $_config = [];
/**
* redis对象
*
* @var \Redis
*/
private $_redis;
/**
* 初始化
*
* @author fdipzone
* @DateTime 2023-03-27 21:50:27
*
* @param array $config redis连接配置
*/
public function __construct(array $config){
$this->_config = $config;
$this->_redis = $this->connect();
}
/**
* 执行自增计数并获取自增后的数值
*
* @author fdipzone
* @DateTime 2023-03-27 21:52:07
*
* @param string $key 保存计数的键值
* @param int $incr 自增数量,默认为1
* @return int
*/
public function incr(string $key, int $incr=1):int{
return intval($this->_redis->incr($key, $incr));
}
/**
* 获取当前计数
*
* @author fdipzone
* @DateTime 2023-03-27 21:53:20
*
* @param string $key 保存计数的键值
* @return int
*/
public function get(string $key):int{
return intval($this->_redis->get($key));
}
/**
* 重置计数
*
* @author fdipzone
* @DateTime 2023-03-27 21:54:03
*
* @param string $key 保存计数的健值
* @return int
*/
public function reset(string $key):int{
return $this->_redis->del($key);
}
/**
* 创建redis连接
*
* @author fdipzone
* @DateTime 2023-03-27 21:54:55
*
* @return \Redis
*/
private function connect():\Redis{
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']);
}
$redis->select($this->_config['index']);
}catch(\Throwable $e){
throw new \Exception($e->getMessage());
}
return $redis;
}
}
?>