代码如下:
IPLimiter.java 定义注解类,将注解定义在需要分流IP的接口上
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IpLimiter {
/**
* 放行ip
*/
String[] ipAdress() default {""};
/**
* 单位时间限制通过请求数
*/
long limit() default 10;
/**
* 单位时间,单位秒
*/
long time() default 1;
/**
* 达到限流提示语
*/
String message();
/**
* 是否锁住IP的同时锁住URI
*/
boolean lockUri() default false;
}
IpLimterHandler.java 注解AOP处理。
import com.missionex.common.annotation.IpLimiter;
import com.missionex.common.core.domain.AjaxResult;
import com.missionex.common.utils.DateUtils;
import com.missionex.common.utils.SecurityUtils;
import com.missionex.common.utils.http.IPAddressUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
@Aspect
@Component
public class IpLimterHandler {
private static final Logger LOGGER = LoggerFactory.getLogger("request-limit");
@Autowired
StringRedisTemplate redisTemplate;
/**
* getRedisScript 读取脚本工具类
* 这里设置为Long,是因为ipLimiter.lua 脚本返回的是数字类型
*/
private DefaultRedisScript<Long> getRedisScript;
@PostConstruct
public void init() {
getRedisScript = new DefaultRedisScript<>();
getRedisScript.setResultType(Long.class);
getRedisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("ipLimiter.lua")));
LOGGER.info("IpLimterHandler[分布式限流处理器]脚本加载完成");
}
/**
* 这个切点可以不要,因为下面的本身就是个注解
*/
// @Pointcut("@annotation(com.jincou.iplimiter.annotation.IpLimiter)")
// public void rateLimiter() {}
/**
* 如果保留上面这个切点,那么这里可以写成
* @Around("rateLimiter()&&@annotation(ipLimiter)")
*/
@Around("@annotation(ipLimiter)")
public Object around(ProceedingJoinPoint proceedingJoinPoint, IpLimiter ipLimiter) throws Throwable {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("IpLimterHandler[分布式限流处理器]开始执行限流操作");
}
String userIp = null;
String requestURI = null;
try {
// 获取请求信息
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
requestURI = request.getRequestURI();
String requestMethod = request.getMethod();
String remoteAddr = request.getRemoteAddr();
// 获取请求用户IP
userIp = IPAddressUtils.getIpAdrress(request);
if (userIp == null) {
return AjaxResult.error("运行环境存在风险");
}
} catch (Exception e) {
LOGGER.error("获取request出错=>" + e.getMessage());
if (userIp == null) {
return AjaxResult.error("运行环境存在风险");
}
}
Signature signature = proceedingJoinPoint.getSignature();
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("the Annotation @IpLimter must used on method!");
}
/**
* 获取注解参数
*/
// 放行模块IP
String[] limitIp = ipLimiter.ipAdress();
int len;
if (limitIp != null && (len = limitIp.length) != 0) {
for (int i = 0; i < len; i++) {
if (limitIp[i].equals(userIp)) {
return proceedingJoinPoint.proceed();
}
}
}
// 限流阈值
long limitTimes = ipLimiter.limit();
// 限流超时时间
long expireTime = ipLimiter.time();
boolean lockUri = ipLimiter.lockUri();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("IpLimterHandler[分布式限流处理器]参数值为-limitTimes={},limitTimeout={}", limitTimes, expireTime);
}
// 限流提示语
String message = ipLimiter.message();
/**
* 执行Lua脚本
*/
List<String> ipList = new ArrayList();
// 设置key值为注解中的值
if (lockUri) {
ipList.add(userIp+requestURI);
} else {
ipList.add(userIp);
}
/**
* 调用脚本并执行
*/
try {
Object x = redisTemplate.execute(getRedisScript, ipList, expireTime+"", limitTimes+"");
Long result = (Long) x;
if (result == 0) {
Long userId = null;
try {
userId = SecurityUtils.getLoginUser().getAppUser().getId();
} catch (Exception e) {
}
LOGGER.info("[分布式限流处理器]限流执行结果-ip={}-接口={}-用户ID={}-result={}-time={},已被限流", userIp,requestURI == null?"未知":requestURI
,userId==null?"用户未登录":userId,result, DateUtils.getTime());
// 达到限流返回给前端信息
return AjaxResult.error(message);
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("IpLimterHandler[分布式限流处理器]限流执行结果-result={},请求[正常]响应", result);
}
return proceedingJoinPoint.proceed();
} catch (Exception e) {
LOGGER.error("限流错误",e);
return proceedingJoinPoint.proceed();
}
}
}
ipLimiter.lua 脚本,放在resources文件夹中。
--获取KEY
local key1 = KEYS[1]
local val = redis.call('incr', key1)
local ttl = redis.call('ttl', key1)
--获取ARGV内的参数并打印
local expire = ARGV[1]
local times = ARGV[2]
redis.log(redis.LOG_DEBUG,tostring(times))
redis.log(redis.LOG_DEBUG,tostring(expire))
redis.log(redis.LOG_NOTICE, "incr "..key1.." "..val);
if val == 1 then
redis.call('expire', key1, tonumber(expire))
else
if ttl == -1 then
redis.call('expire', key1, tonumber(expire))
end
end
if val > tonumber(times) then
return 0
end
return 1
RedisConfig.java redis配置(该配置继承了CachingConfigurerSupport)中对写入redis的数据的序列化。
如果使用IP锁的时候,错误出现在了AOP中的使用脚本写入redis的时候(像什么Long无法转String的错误),基本是这边序列化没配好。
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
// Hash的key也采用StringRedisSerializer的序列化方式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
使用示范。
@PostMapping("/test")
@IpLimiter(limit = 2, time = 5, message = "您访问过于频繁,请稍候访问",lockUri = true)
public AjaxResult test(@RequestBody Map map){
//代码......
}