class RedisLimit
{
static $oneITime = 60;
static $oneIMax = 50;
static $platITime = 60;
static $platIMax = 10;
const REDIS_CONFIG_HOST = '127.0.0.1';
const REDIS_CONFIG_PORT = 6379;
public static function redis_lock_all_limit()
{
$redis = self::getRedisConn();
$platKey = md5(request()->url());
$platFlowCount = $redis->get($platKey);
if($platFlowCount){
if($platFlowCount >= self::$platIMax){
return json(['code'=>0,'msg'=>'超過訪問次數']);
}
}
$redis->incr($platKey);
!$platFlowCount && $redis->expire($platKey,self::$platITime);
return json(['code'=>1,'msg'=>'透過']);
}
public static function redis_lock_single_limit($mer_no)
{
$redis = self::getRedisConn();
$key = md5($mer_no.":".request()->ip());
$userFlowCount = $redis->get($key);
if($userFlowCount){
if($userFlowCount >= self::$oneIMax){
return json(['code'=>0,'msg'=>'超過訪問次數']);
}
}
$redis->incr($key);
!$userFlowCount && $redis->expire($key,self::$oneITime);
}
public static function getRedisConn($strIp = self::REDIS_CONFIG_HOST, $intPort = self::REDIS_CONFIG_PORT)
{
try {
if (!extension_loaded('redis')) {
throw new \BadFunctionCallException('not support: redis');
}
$objRedis = new \Redis();
$objRedis->connect($strIp, $intPort);
return $objRedis;
}catch (Exception $exception){
throw new Exception($exception->getMessage());
}
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結