Lavavel5.5源代码 - 限流工具
app('redis')->connection('default')->throttle('key000')
// 每60秒,只能有10个资源被获取,在3秒内获取不到锁抛出异常
->allow(10)->every(60)->block(3)
->then(function () {
// 获取锁成功,执行业务
}, function () {
// 获取锁失败
return false;
});
<?php namespace Illuminate\Redis\Limiters; use Illuminate\Contracts\Redis\LimiterTimeoutException; class DurationLimiter
{
/**
* The Redis factory implementation.
*
* @var \Illuminate\Redis\Connections\Connection
*/
private $redis; /**
* The unique name of the lock.
*
* @var string
*/
private $name; /**
* The allowed number of concurrent tasks.
*
* @var int
*/
private $maxLocks; /**
* The number of seconds a slot should be maintained.
*
* @var int
*/
private $decay; /**
* The timestamp of the end of the current duration.
*
* @var int
*/
public $decaysAt; /**
* The number of remaining slots.
*
* @var int
*/
public $remaining; /**
* Create a new duration limiter instance.
*
* @param \Illuminate\Redis\Connections\Connection $redis
* @param string $name
* @param int $maxLocks
* @param int $decay
* @return void
*/
public function __construct($redis, $name, $maxLocks, $decay)
{
$this->name = $name;
$this->decay = $decay;
$this->redis = $redis;
$this->maxLocks = $maxLocks;
} /**
* Attempt to acquire the lock for the given number of seconds.
*
* @param int $timeout
* @param callable|null $callback
* @return bool
* @throws \Illuminate\Contracts\Redis\LimiterTimeoutException
*/
public function block($timeout, $callback = null)
{
$starting = time(); while (! $this->acquire()) {
if (time() - $timeout >= $starting) {
throw new LimiterTimeoutException;
} usleep(750 * 1000);
} if (is_callable($callback)) {
$callback();
} return true;
} /**
* Attempt to acquire the lock.
*
* @return bool
*/
public function acquire()
{
$results = $this->redis->eval($this->luaScript(), 1,
$this->name, microtime(true), time(), $this->decay, $this->maxLocks
); $this->decaysAt = $results[1]; $this->remaining = max(0, $results[2]); return (bool) $results[0];
} /**
* Get the Lua script for acquiring a lock.
*
* KEYS[1] - The limiter name
* ARGV[1] - Current time in microseconds
* ARGV[2] - Current time in seconds
* ARGV[3] - Duration of the bucket
* ARGV[4] - Allowed number of tasks
*
* @return string
*/
protected function luaScript()
{
return <<<'LUA'
local function reset()
redis.call('HMSET', KEYS[1], 'start', ARGV[2], 'end', ARGV[2] + ARGV[3], 'count', 1)
return redis.call('EXPIRE', KEYS[1], ARGV[3] * 2)
end if redis.call('EXISTS', KEYS[1]) == 0 then
return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
end if ARGV[1] >= redis.call('HGET', KEYS[1], 'start') and ARGV[1] <= redis.call('HGET', KEYS[1], 'end') then
return {
tonumber(redis.call('HINCRBY', KEYS[1], 'count', 1)) <= tonumber(ARGV[4]),
redis.call('HGET', KEYS[1], 'end'),
ARGV[4] - redis.call('HGET', KEYS[1], 'count')
}
end return {reset(), ARGV[2] + ARGV[3], ARGV[4] - 1}
LUA;
}
}
Lavavel5.5源代码 - 限流工具的更多相关文章
- Guava限流工具RateLimiter使用
公司最近在推一个限流工具接入,提供的功能有单机限流.集群限流等.想了解一下限流的原理和设计,看了一下wiki里面有提到用了guava的ratelimiter工具,查了一些资料了解了一下 主要的限流算法 ...
- guava的限流工具RateLimiter使用
guava限流工具使用 非常详细的一篇使用博客:https://www.cnblogs.com/yeyinfu/p/7316972.html 1,原理:Guava RateLimiter基于令牌桶算法 ...
- java限流工具类
代码 import com.google.common.util.concurrent.RateLimiter; import java.util.concurrent.ConcurrentHashM ...
- java高并发系列 - 第15天:JUC中的Semaphore,最简单的限流工具类,必备技能
这是java高并发系列第15篇文章 Semaphore(信号量)为多线程协作提供了更为强大的控制方法,前面的文章中我们学了synchronized和重入锁ReentrantLock,这2种锁一次都只能 ...
- Spring Cloud Zuul 限流详解(附源码)(转)
在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Cloud中如何实现限流. 在 Zuul 上实现限流是个不错的选择,只需要编写一个过滤器就可以了,关键在于如何实现限流的算法. ...
- 高并发之API接口限流
在开发高并发系统时有三把利器用来保护系统:缓存.降级和限流 缓存 缓存的目的是提升系统访问速度和增大系统处理容量 降级 降级是当服务出现问题或者影响到核心流程时,需要暂时屏蔽掉,待高峰或者问题解决后再 ...
- Spring Cloud限流详解
转自:https://blog.csdn.net/tracy38/article/details/78685707 在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Cloud ...
- Spring Cloud限流思路及解决方案
转自: http://blog.csdn.net/zl1zl2zl3/article/details/78683855 在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Clo ...
- Spring Cloud(十二):Spring Cloud Zuul 限流详解(附源码)(转)
前面已经介绍了很多zuul的功能,本篇继续介绍它的另一大功能.在高并发的应用中,限流往往是一个绕不开的话题.本文详细探讨在Spring Cloud中如何实现限流. 在 Zuul 上实现限流是个不错的选 ...
随机推荐
- .NET开源工作流RoadFlow-表单设计-组织机构选择
组织机构选择即在表单中添加组织机构选择框. 选择范围: 1.发起者部门:只能在发起者同一个部门中选择. 2.处理者部门:只能在当前处理者同一个部门中选择. 3.自定义:自己指定一个选择范围. 选择类型 ...
- SharePoint 2013 - Designer Workflow
另一篇文章 SharePoint Designer - Workflow 1. 可以定义每个Stage的名称,并将Stage名称显示在工作流状态字段,相比于SP2010时仅有的in progress ...
- SharePoint 2013 - Client OM
1. 向 executeQueryAsync 中传递参数可以使用以下两种方式,也可以参考这篇文章: var mySuccessCallBack = Function.createCallback(on ...
- 安装lombok(eclipse)
下载 lombok.jar (https://projectlombok.org/download.html) 将 lombok.jar 放在eclipse安装目录下,和 eclipse.ini 文件 ...
- win7下tomcat5.5无法通过ip和127.0.0.1访问的解决方法
解决办法:找到tomcat5.5目录下的conf\server.xml文件,原文如下: <Connector port="8080" maxHttpHeaderSize=&q ...
- PowerDesigner 连接数据库(以MySQL)为例
- asyncio标准库3 HTTP client example
import aiohttp import asyncio import async_timeout async def fetch(session, url): async with async_t ...
- sqlserver学习2---java执行存储过程
一.存储过程 1.新增操作存储过程 --------------1.新建 增加学生的存储过程---------------------------- set IDENTITY_INSERT stude ...
- leetcode 322零钱兑换
You are given coins of different denominations and a total amount of money amount. Write a function ...
- OC static 和变量
#include <stdio.h> // 如果在不同源文件出现了同名的内部变量,那么这些变量将互不干扰 static int b; // 用static修饰的全部变量,可以称为内部变量 ...