Skip to content

Commit

Permalink
Cache buckets as local variables to avoid extra hop to redis. (#851)
Browse files Browse the repository at this point in the history
  • Loading branch information
Reasno authored and limingxinleo committed Nov 7, 2019
1 parent c711676 commit f40e7d4
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -22,6 +22,7 @@

- [#832](https://github.com/hyperf/hyperf/pull/832) Optimized that response will throw a exception when json format failed.
- [#840](https://github.com/hyperf/hyperf/pull/840) Use `\Swoole\Timer::*` to instead of `swoole_timer_*` functions.
- [#851](https://github.com/hyperf/hyperf/pull/851) Cache buckets as local variables to avoid extra hop to redis.

# v1.1.4 - 2019-10-31

Expand Down
13 changes: 12 additions & 1 deletion src/rate-limit/src/Aspect/RateLimitAnnotationAspect.php
Expand Up @@ -13,6 +13,7 @@
namespace Hyperf\RateLimit\Aspect;

use bandwidthThrottle\tokenBucket\storage\StorageException;
use bandwidthThrottle\tokenBucket\TokenBucket;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Aop\AroundInterface;
Expand Down Expand Up @@ -54,6 +55,11 @@ class RateLimitAnnotationAspect implements AroundInterface
*/
private $rateLimitHandler;

/**
* @var array<string, TokenBucket>
*/
private $buckets = [];

public function __construct(ConfigInterface $config, RequestInterface $request, RateLimitHandler $rateLimitHandler)
{
$this->annotationProperty = get_object_vars(new RateLimit());
Expand All @@ -78,7 +84,12 @@ public function process(ProceedingJoinPoint $proceedingJoinPoint)
$bucketKey = $this->request->getUri()->getPath();
}

$bucket = $this->rateLimitHandler->build($bucketKey, $annotation->create, $annotation->capacity, $annotation->waitTimeout);
if (isset($this->buckets[$bucketKey])) {
$bucket = $this->buckets[$bucketKey];
} else {
$bucket = $this->rateLimitHandler->build($bucketKey, $annotation->create, $annotation->capacity, $annotation->waitTimeout);
$this->buckets[$bucketKey] = $bucket;
}

$maxTime = microtime(true) + $annotation->waitTimeout;
$seconds = 0;
Expand Down

0 comments on commit f40e7d4

Please sign in to comment.