高并发的情况下,过滤黑名单。使用redis的zset(有序集合)判断,ip是否属于其中。
/**
* Notes: 判断iP是否在黑名单数据中
* User: kudaren
* Date: 2023/2/24 17:54
*/
public function IpIsset(){
$ip = input('ip');
$redisKey='ipList';
$ttl = $this->redis->ttl($redisKey);//判断值是否过期
if ($ttl < 2) {//如果有效期少于2秒或已经过期
$this->initCache($redisKey);//重新生成缓存
}
$res = $this->redis->zScore($redisKey, $ip);//判断ip是否在集合中
return $res ? 1 : 0;//存在返回集合的score
}
/**
* Notes:重新生成缓存
* User: kudaren
* Date: 2023/2/24 17:59
*/
public function initCache($redisKey){
$data=[1,'192.168.1.1',2,'192.168.1.2'];//顺序是score,value
$this->redis->zAdd($redisKey, ...$data);//批量插入,注意三个点的写法
$this->redis->expire($redisKey, 86400);//设置过期时间一小时
}