Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
P
php_utils
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
bp
php_utils
Commits
6495e3a3
Commit
6495e3a3
authored
Jul 10, 2021
by
cuiweifeng
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
add : 频率锁
parent
4ca547ae
Changes
1
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
83 additions
and
0 deletions
+83
-0
FrequencyLockUtil.php
src/Lock/FrequencyLockUtil.php
+83
-0
No files found.
src/Lock/FrequencyLockUtil.php
0 → 100644
View file @
6495e3a3
<?php
namespace
Api\PhpUtils\Lock
;
/**
* Redis 频率锁
*/
use
Api\PhpUtils\Redis\RedisUtil
;
class
FrequencyLockUtil
{
const
MIN_FREQUENCY_SECONDS
=
30
;
// 频率锁默认最小间隔秒数
const
MIN_FREQUENCY_TIMES
=
1
;
// 频率锁默认最小间隔秒数内最大访问次数
const
PREFIX_FREQUENCY_LOCK
=
'flk:'
;
private
static
$handler
=
null
;
private
static
function
initCache
()
{
if
(
empty
(
self
::
$handler
)){
//获取连接句柄, 使用gateway的codis
self
::
$handler
=
RedisUtil
::
getInstance
(
'cache'
,
[
'serializer'
=>
'none'
]);
}
}
/**
* 频率锁, 每$expire秒钟允许$times次$key访问
*
* @param string $key 锁定的key
* @param int $times 允许访问次数
* @param int $expire 锁定时长,秒数
* @return boolean
*/
public
static
function
isLocked
(
$key
,
$times
=
self
::
MIN_FREQUENCY_TIMES
,
$expire
=
self
::
MIN_FREQUENCY_SECONDS
)
{
$key
=
self
::
PREFIX_FREQUENCY_LOCK
.
$key
;
self
::
initCache
();
$current_times
=
self
::
$handler
->
incr
(
$key
);
if
(
$current_times
==
1
)
{
self
::
$handler
->
expire
(
$key
,
$expire
);
}
return
(
$current_times
>
$times
)
?
false
:
true
;
}
/**
* 频次减少
* @param string $key 锁定的key
* @param int $number 减少的值
* @return void
*/
public
static
function
decr
(
$key
,
$number
=
1
)
{
$key
=
self
::
PREFIX_FREQUENCY_LOCK
.
$key
;
self
::
initCache
();
return
self
::
$handler
->
decrby
(
$key
,
$number
);
}
/**
* 频次重置(测试用)
* @param string $key
*/
public
static
function
reset
(
$key
)
{
$key
=
self
::
PREFIX_FREQUENCY_LOCK
.
$key
;
self
::
initCache
();
return
self
::
$handler
->
del
(
$key
);
}
/**
* 已经使用次数
* @param string $key
* @return int
*/
public
static
function
get
(
$key
)
{
$key
=
self
::
PREFIX_FREQUENCY_LOCK
.
$key
;
self
::
initCache
();
$times
=
self
::
$handler
->
get
(
$key
);
return
intval
(
$times
);
}
}
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment