PHP code example of wilbur-yu / hyperf-cache-ext
1. Go to this page and download the library: Download wilbur-yu/hyperf-cache-ext library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
wilbur-yu / hyperf-cache-ext example snippets
'default' => [
'driver' => WilburYu\HyperfCacheExt\Driver\RedisDriver::class,
'packer' => WilburYu\HyperfCacheExt\Utils\Packer\PhpSerializerPacker::class,
'prefix' => env('APP_NAME', 'skeleton').':cache:',
],
'limiter' => [
'prefix' => 'rate-limit:', // key前缀
'max_attempts' => 20, // 最大允许数
'decay_minutes' => 60, // 限流单位时间
'wait' => 250, // 并发时, 获取锁最大等待毫秒数
'timeout' => 1, // 并发时, 获取锁超时秒数
'for' => [
'common' => static function (\Hyperf\HttpServer\Contract\RequestInterface $request) {
return Limit::perMinute(3);
},
],
'key' => ThrottleRequest::key(),
],
#[CounterRateLimiterWithRedis(maxAttempts: 5, decayMinutes: 1)]
or
#[CounterRateLimiter(for: "common")]
use WilburYu\HyperfCacheExt\Annotation\ConcurrencyRateLimiter;
// 1秒内最高支持并发请求5次
#[ConcurrencyRateLimiter(key: 'get.posts', maxAttempts: 5, decayMinutes: 1, timeout: 1, wait: 250)]
use WilburYu\HyperfCacheExt\Annotation\DurationRateLimiter;
// 每 10 秒最多支持 100 个请求
#[DurationRateLimiter(key: 'get.posts', maxAttempts: 100, decayMinutes: 10, timeout: 1, wait: 750)]
-
$executed = counter_limiter()->attempt('send-sms:'.$user->id,2,function(){
// send sms logic
});
if (!$executed) {
return 'Too many messages sent!';
}
$executed = concurrency_limiter('key')->limit(100)->then(function(){
// send sms logic
}, function(){
// 异常上时调用
abort(429);
});
$executed = duration_limiter('key')->allow(100)->every(10)->then(function(){
// send sms logic
}, function(){
// 异常上时调用
abort(429);
});