/**
* 基于redis的限流
* @author: whh
* @date: 2020.03.19
**/
public class RedisRateLimitUtil {
public static final Logger LOGGER = LoggerFactory.getLogger(RedisRateLimitUtil.class);
@Resource(name = "anticheatRedisClient")
private RedisClient anticheatRedisClient;
public boolean tryAcquire(String key, int timeWindow, int limitNum) {
boolean acquireResult = anticheatRedisClient.execute(key, new JedisAction<Boolean>() {
@Override
public Boolean action(Jedis jedis) {
try {
String setNxResult = jedis.set(key, "1", "NX", "EX", timeWindow);
if ("OK".equals(setNxResult)) {
return true;
}
Long num = jedis.incr(key);
if (num == 1) {
jedis.expire(key, timeWindow);
}
if (num > limitNum) {
return false;
}
return true;
} catch (Exception e) {
LOGGER.error("acquireResult error", e);
}
return true;
}
});
return acquireResult;
}
}