问:问题描述:
主要内容是防止用户发出恶意请求并限制每单位时间的访问次数,
然后进行了AOP,但我无法在控制器层获得AOP方法的返回值,如图所示。以下代码:
@Pointcut("execution(public * com.mzd.redis_springboot_mybatis_mysql.controller.*.*(..))")
public void WebPointCut() {
}
@Before("WebPointCut() && @annotation(times)")
public boolean ifovertimes(final JoinPoint joinPoint, RequestTimes times) {
try {
Object[] objects = joinPoint.getArgs();
HttpServletRequest request = null;
for (int i = 0; i < objects.length; i++) {
if (objects[i] instanceof HttpServletRequest) {
request = (HttpServletRequest) objects[i];
break;
}
}
if (request == null) {
return true;
}
String ip = request.getRemoteAddr();
String url = request.getRequestURL().toString();
String key = "ifovertimes".concat(url).concat(ip);
long count = redisTemplate.opsForValue().increment(key, 1);
//If it is the first time, set the expiration time
if (count == 1) {
redisTemplate.expire(key, times.time(), TimeUnit.MILLISECONDS);
}
if (count <= times.count()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
然后我想知道如何在控制器层中获取布尔值,无论它是否已达到最大访问次数
答:在这种情况下,应使用@环绕声注入。当判断超过限制时间时,直接返回异常信息,不再执行控制器方法;
另外,控制器可以依靠AOP的返回值,但这不是一个好的程序设计,这违反了AOP的初衷。
答:这是代码〜
@Around("...")
public Object controllerLogAround(ProceedingJoinPoint pjp) throws Throwable {
...
//Method parameters
Object[] methodArgs = pjp.getArgs();
//Call and get the return value
Object returnValue = pjp.proceed(methodArgs);
...
return returnValue;
}