一、接口的安全性
二、实现自定义的注解
import JAVA.lang.Annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;import static java.lang.annotation.ElementType.METHOD;@Retention(RetentionPolicy.RUNTIME)@Target(METHOD)@Documentedpublic @interface RateLimit {String cycle() default "5"; //请求等待的时间String number() default "1"; //短时间内多少次的请求String msg() default "请求繁忙,请稍后点击";
三、切面代码的实现
import com.south.wires.config.annotation.RateLimit;import com.south.wires.result.JsonResult;import lombok.extern.slf4j.Slf4j;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.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.script.DefaultRedisScript;import org.springframework.data.redis.serializer.StringRedisSerializer;import org.springframework.stereotype.Component;import org.springframework.web.context.Request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;import java.lang.reflect.Method;import java.util.Collections;@Slf4j@Aspect@Componentpublic class RateLimitAspect {@Autowiredprivate RedisTemplate redisTemplate;@Around("@annotation(com.xxx.xxx.config.annotation.RateLimit)")public JsonResult around(ProceedingJoinPoint joinPoint) throws Throwable {// 业务方法执行之前设置数据源...Boolean pass=doingSomthingBefore(joinPoint);Object result;if(pass){// 执行业务方法result =joinPoint.proceed();}else{// 业务方法执行之后清除数据源设置...result=doingSomthingAfter(joinPoint);//自定义的返回值的类型return JsonResult.success(result);private boolean doingSomthingBefore(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {// 接收到请求,记录请求内容ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String ip = request.getRemoteAddr();String uri = request.getRequestURI();// 记录下请求内容log.info("请求类型 :" + request.getMethod() + " " + "请求URL : " + request.getRequestURL());log.info("请求IP : " + request.getRemoteAddr());log.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());Method targetMethod=getTargetMethod(joinPoint);return selectLimit(ip, uri,targetMethod);private Method getTargetMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {//获取目标对象对应的字节码对象Class targetCls=joinPoint.getTarget().getClass();//获取方法签名信息从而获取方法名和参数类型Signature signature=joinPoint.getSignature();//将方法签名强转成MethodSignature类型,方便调用MethodSignature ms= (MethodSignature)signature;return targetCls.getDeclaredMethod(ms.getName(),ms.getParameterTypes());private String doingSomthingAfter(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {System.out.println("开始后");//获取方法上的自定义RateLimit注解RateLimit rateLimit=getTargetMethod(joinPoint).getAnnotation(RateLimit.class);return rateLimit.msg();private static final String SCRIPT = "local limit = tonumber(ARGV[1]);"// 限制次数+ "local expire_time = ARGV[2];"// 过期时间+ "local result = redis.call('setNX',KEYS[1],1);"// key不存在时设置value为1,返回1、否则返回0+ "if result == 1 then"// 返回值为1,key不存在此时需要设置过期时间+ " redis.call('expire',KEYS[1],expire_time);"// 设置过期时间+ " return 1; "// 返回1+ "else"// key存在+ " if tonumber(redis.call('GET', KEYS[1])) >= limit then"// 判断数目比对+ " return 0;"// 如果超出限制返回0+ " else" //+ " redis.call('incr', KEYS[1]);"// key自增+ " return 1 ;"// 返回1+ " end "// 结束+ "end";// 结束public Boolean selectLimit(String ip, String url,Method targetMethod) {String key = "custom:rate" + ip + ":" + url;StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();redisTemplate.setValueSerializer(stringRedisSerializer);redisTemplate.setKeySerializer(stringRedisSerializer);DefaultRedisScript defaultRedisScript = new DefaultRedisScript<>(SCRIPT);defaultRedisScript.setResultType(Boolean.class);Boolean execute = null;try {RateLimit rateLimit=targetMethod.getAnnotation(RateLimit.class);execute = (Boolean) redisTemplate.execute(defaultRedisScript, Collections.singletonList(key), rateLimit.number(),rateLimit.cycle());} catch (Exception ex) {ex.printStackTrace();if (!execute) {return false;return true;
四、控制层添加相应的注解
@RateLimit@ResponseBody@RequestMApping("testRateLimit")public Object test2(){System.out.println("执行检索");return "请求成功";
控制层代码执行
接口请求执行成功
接口请求失败