| |
| <?php |
| |
| |
| |
| return [ |
| |
| 'is_enable' => env('WHITE_LIST_IS_ENABLE', 0), |
| |
| |
| 'number' => env('WHITE_LIST_NUMBER', 100), |
| |
| |
| 'cache_key_prefix' => env('WHITE_LIST_CACHE_KEY_PREFIX', 'first'), |
| |
| |
| 'cache_key_list_init' => '_xxx_white_list_init', |
| 'cache_key_list' => '_xxx_white_list', |
| 'cache_key_hash' => '_xxx_white_hash' |
| 'cache_ttl' => 43200, |
| |
| |
| 'error_msg' => 'xxx 系统暂不可用,请稍晚一些再登陆使用,谢谢配合!', |
| ]; |
| |
| |
| <?php |
| |
| namespace App\Services; |
| |
| use Illuminate\Support\Facades\Redis; |
| |
| class RedisHelper |
| { |
| |
| |
| |
| |
| |
| |
| |
| public static function setNxWithTTL(string $key, $value, int $ttl = 300): bool |
| { |
| if ((Redis::connection('default'))->set($key, $value, 'ex', $ttl, 'nx')) { |
| return true; |
| } |
| return false; |
| } |
| } |
| |
| |
| |
| |
| |
| public function isInWhiteList(int $staffId): bool |
| { |
| |
| if (!config('white_list.is_enable')) { |
| return true; |
| } |
| |
| |
| $whiteListNumber = (int)config('white_list.number'); |
| if ($whiteListNumber <= 0) { |
| return false; |
| } |
| |
| $redis = Redis::connection('default'); |
| $cacheKeyPrefix = config('white_list.cache_key_prefix'); |
| $cacheKeyListInit = $cacheKeyPrefix . config('white_list.cache_key_list_init'); |
| $cacheKeyList = $cacheKeyPrefix . config('white_list.cache_key_list'); |
| $cacheKeyHash = $cacheKeyPrefix . config('white_list.cache_key_hash'); |
| $cacheTTL = config('white_list.cache_ttl'); |
| |
| |
| if ($redis->exists($cacheKeyHash) && $redis->hexists($cacheKeyHash, $staffId)) { |
| return true; |
| } |
| |
| |
| if (!$redis->exists($cacheKeyListInit)) { |
| if (!RedisHelper::setNxWithTTL("{$cacheKeyListInit}_nx", 1, config('cache.one_hour'))) { |
| return true; |
| } |
| |
| $redis->rpush($cacheKeyListInit, array_fill(0, $whiteListNumber, 1)); |
| $redis->expire($cacheKeyListInit, $cacheTTL); |
| } |
| |
| |
| $length = $redis->llen($cacheKeyListInit); |
| if ($length < $whiteListNumber) { |
| if (!RedisHelper::setNxWithTTL("{$cacheKeyListInit}_nx_{$whiteListNumber}", 1, config('cache.one_hour'))) { |
| return false; |
| } |
| |
| $redis->rpush($cacheKeyListInit, array_fill($length - 1, $whiteListNumber - $length, 1)); |
| $redis->expire($cacheKeyListInit, $cacheTTL); |
| } |
| |
| |
| if (!$redis->hsetnx($cacheKeyHash, $staffId, 1)) { |
| return true; |
| } |
| |
| $index = $redis->rpush($cacheKeyList, [$staffId]); |
| $ret = $redis->lindex($cacheKeyListInit, $index - 1); |
| |
| |
| if (empty($ret)) { |
| $redis->rpop($cacheKeyList); |
| $redis->hdel($cacheKeyHash, [$staffId]); |
| return false; |
| } |
| |
| $redis->expire($cacheKeyList, $cacheTTL); |
| $redis->expire($cacheKeyHash, $cacheTTL); |
| |
| return true; |
| } |