個(gè)人網(wǎng)站 不用備案朋友圈廣告
承接上文(傳送門 —>《面試必考》 — AOP-CSDN博客),在被面試官拷打的時(shí)候,會(huì)被問到一個(gè)致命問題:“你了解aop嗎?有具體的使用經(jīng)驗(yàn)嗎?”
你:.........
言盡于此,此篇文章必能大補(bǔ)
自定義注解①:連續(xù)點(diǎn)擊注解
package com.ruoyi.profile.lock;import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLock {String key() default ""; // 主鍵前綴long duration() default 2000; // 默認(rèn)防抖時(shí)間,單位毫秒boolean useIp() default true; // 是否使用IP作為鍵的一部分boolean useUserId() default true; // 是否使用用戶ID作為鍵的一部分
}package com.ruoyi.profile.lock;import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;import static com.ruoyi.common.constant.HttpStatus.WARN;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;@Aspect
@Component
@Order(2)
public class RequestLockAspect {@Resourceprivate StringRedisTemplate stringRedisTemplate;@Around("execution(public * * (..)) && @annotation(requestLock)")public Object handleDebounce(ProceedingJoinPoint joinPoint, RequestLock requestLock) throws Throwable {String key = generateKey(joinPoint, requestLock);Object proceed = joinPoint.proceed();if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(key))) {stringRedisTemplate.opsForValue().set(key, "true", requestLock.duration(), TimeUnit.MILLISECONDS);return proceed;} else {if (proceed instanceof TableDataInfo) {TableDataInfo rspData = new TableDataInfo();rspData.setCode(WARN);rspData.setMsg("請(qǐng)求太頻繁,請(qǐng)稍后再試!!!");return rspData;} else if (proceed instanceof AjaxResult) {// 返回一個(gè)默認(rèn)值或拋出異常,根據(jù)業(yè)務(wù)需求決定return AjaxResult.error("請(qǐng)求太頻繁,請(qǐng)稍后再試!!!");} else {throw new RuntimeException("未知返回錯(cuò)誤");}}}private String generateKey(ProceedingJoinPoint joinPoint, RequestLock requestLock) {HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();StringBuilder sb = new StringBuilder();Object[] args = joinPoint.getArgs();for (Object arg : args) {sb.append(":").append(arg.toString());}// 根據(jù)注解參數(shù)構(gòu)建鍵sb.append(requestLock.key());if (requestLock.useIp()) {sb.append(":").append(request.getRemoteAddr()); // 獲取客戶端IP}if (requestLock.useUserId()) {// 假設(shè)用戶ID可以從某個(gè)地方獲取,比如從session或token中Long userId = getLoginUser().getUserId();sb.append(":").append(userId);}return sb.toString();}}
自定義注解②:限流注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.enums.LimitType;/*** 限流注解* * @author */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter
{/*** 限流key*/public String key() default CacheConstants.RATE_LIMIT_KEY;/*** 限流時(shí)間,單位秒*/public int time() default 60;/*** 限流次數(shù)*/public int count() default 100;/*** 限流類型*/public LimitType limitType() default LimitType.DEFAULT;
}import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.RateLimiter;
import com.ruoyi.common.enums.LimitType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;/*** 限流處理** @author */
@Aspect
@Component
public class RateLimiterAspect
{private static final Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);private RedisTemplate<Object, Object> redisTemplate;private RedisScript<Long> limitScript;@Autowiredpublic void setRedisTemplate1(RedisTemplate<Object, Object> redisTemplate){this.redisTemplate = redisTemplate;}@Autowiredpublic void setLimitScript(RedisScript<Long> limitScript){this.limitScript = limitScript;}@Before("@annotation(rateLimiter)")public void doBefore(JoinPoint point, RateLimiter rateLimiter) throws Throwable{int time = rateLimiter.time();int count = rateLimiter.count();String combineKey = getCombineKey(rateLimiter, point);List<Object> keys = Collections.singletonList(combineKey);try{Long number = redisTemplate.execute(limitScript, keys, count, time);if (StringUtils.isNull(number) || number.intValue() > count){throw new ServiceException("訪問過于頻繁,請(qǐng)稍候再試");}log.info("限制請(qǐng)求'{}',當(dāng)前請(qǐng)求'{}',緩存key'{}'", count, number.intValue(), combineKey);}catch (ServiceException e){throw e;}catch (Exception e){throw new RuntimeException("服務(wù)器限流異常,請(qǐng)稍候再試");}}public String getCombineKey(RateLimiter rateLimiter, JoinPoint point){StringBuffer stringBuffer = new StringBuffer(rateLimiter.key());if (rateLimiter.limitType() == LimitType.IP){stringBuffer.append(IpUtils.getIpAddr()).append("-");}MethodSignature signature = (MethodSignature) point.getSignature();Method method = signature.getMethod();Class<?> targetClass = method.getDeclaringClass();stringBuffer.append(targetClass.getName()).append("-").append(method.getName());return stringBuffer.toString();}
}
限流方式其實(shí)有很多種,比如說:Nginx漏桶算法、Gateway令牌桶算法、Sentinel、CircuitBreaker、自定義注解限流、自定義過濾器、自定義攔截器等等。
Gateway參考鏈接:Spring Cloud Gateway 限流詳解-騰訊云開發(fā)者社區(qū)-騰訊云 (tencent.com)
如果不明白最后三個(gè)的區(qū)別,傳送門 —>《面試必考》 — AOP-CSDN博客
自定義注解③:日志注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;/*** 自定義操作日志記錄注解* * @author **/
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log
{/*** 模塊*/public String title() default "";/*** 功能*/public BusinessType businessType() default BusinessType.OTHER;/*** 操作人類別*/public OperatorType operatorType() default OperatorType.MANAGE;/*** 是否保存請(qǐng)求的參數(shù)*/public boolean isSaveRequestData() default true;/*** 是否保存響應(yīng)的參數(shù)*/public boolean isSaveResponseData() default true;/*** 排除指定的請(qǐng)求參數(shù)*/public String[] excludeParamNames() default {};
}package com.ruoyi.framework.aspectj;import java.util.Collection;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.enums.HttpMethod;
import com.ruoyi.common.filter.PropertyPreExcludeFilter;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.SysOperLog;/*** 操作日志記錄處理* * @author */
@Aspect
@Component
public class LogAspect
{private static final Logger log = LoggerFactory.getLogger(LogAspect.class);/** 排除敏感屬性字段 */public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" };/** 計(jì)算操作消耗時(shí)間 */private static final ThreadLocal<Long> TIME_THREADLOCAL = new NamedThreadLocal<Long>("Cost Time");/*** 處理請(qǐng)求前執(zhí)行*/@Before(value = "@annotation(controllerLog)")public void boBefore(JoinPoint joinPoint, Log controllerLog){TIME_THREADLOCAL.set(System.currentTimeMillis());}/*** 處理完請(qǐng)求后執(zhí)行** @param joinPoint 切點(diǎn)*/@AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult")public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult){handleLog(joinPoint, controllerLog, null, jsonResult);}/*** 攔截異常操作* * @param joinPoint 切點(diǎn)* @param e 異常*/@AfterThrowing(value = "@annotation(controllerLog)", throwing = "e")public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e){handleLog(joinPoint, controllerLog, e, null);}protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult){try{// 獲取當(dāng)前的用戶LoginUser loginUser = SecurityUtils.getLoginUser();// *========數(shù)據(jù)庫(kù)日志=========*//SysOperLog operLog = new SysOperLog();operLog.setStatus(BusinessStatus.SUCCESS.ordinal());// 請(qǐng)求的地址String ip = IpUtils.getIpAddr();operLog.setOperIp(ip);operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));if (loginUser != null){operLog.setOperName(loginUser.getUsername());SysUser currentUser = loginUser.getUser();if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept())){operLog.setDeptName(currentUser.getDept().getDeptName());}}if (e != null){operLog.setStatus(BusinessStatus.FAIL.ordinal());operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));}// 設(shè)置方法名稱String className = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();operLog.setMethod(className + "." + methodName + "()");// 設(shè)置請(qǐng)求方式operLog.setRequestMethod(ServletUtils.getRequest().getMethod());// 處理設(shè)置注解上的參數(shù)getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult);// 設(shè)置消耗時(shí)間operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get());// 保存數(shù)據(jù)庫(kù)AsyncManager.me().execute(AsyncFactory.recordOper(operLog));}catch (Exception exp){// 記錄本地異常日志log.error("異常信息:{}", exp.getMessage());exp.printStackTrace();}finally{TIME_THREADLOCAL.remove();}}/*** 獲取注解中對(duì)方法的描述信息 用于Controller層注解* * @param log 日志* @param operLog 操作日志* @throws Exception*/public void getControllerMethodDescription(JoinPoint joinPoint, Log log, SysOperLog operLog, Object jsonResult) throws Exception{// 設(shè)置action動(dòng)作operLog.setBusinessType(log.businessType().ordinal());// 設(shè)置標(biāo)題operLog.setTitle(log.title());// 設(shè)置操作人類別operLog.setOperatorType(log.operatorType().ordinal());// 是否需要保存request,參數(shù)和值if (log.isSaveRequestData()){// 獲取參數(shù)的信息,傳入到數(shù)據(jù)庫(kù)中。setRequestValue(joinPoint, operLog, log.excludeParamNames());}// 是否需要保存response,參數(shù)和值if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)){operLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000));}}/*** 獲取請(qǐng)求的參數(shù),放到log中* * @param operLog 操作日志* @throws Exception 異常*/private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception{Map<?, ?> paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest());String requestMethod = operLog.getRequestMethod();if (StringUtils.isEmpty(paramsMap)&& (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod))){String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames);operLog.setOperParam(StringUtils.substring(params, 0, 2000));}else{operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000));}}/*** 參數(shù)拼裝*/private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames){String params = "";if (paramsArray != null && paramsArray.length > 0){for (Object o : paramsArray){if (StringUtils.isNotNull(o) && !isFilterObject(o)){try{String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames));params += jsonObj.toString() + " ";}catch (Exception e){}}}}return params.trim();}/*** 忽略敏感屬性*/public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames){return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames));}/*** 判斷是否需要過濾的對(duì)象。* * @param o 對(duì)象信息。* @return 如果是需要過濾的對(duì)象,則返回true;否則返回false。*/@SuppressWarnings("rawtypes")public boolean isFilterObject(final Object o){Class<?> clazz = o.getClass();if (clazz.isArray()){return clazz.getComponentType().isAssignableFrom(MultipartFile.class);}else if (Collection.class.isAssignableFrom(clazz)){Collection collection = (Collection) o;for (Object value : collection){return value instanceof MultipartFile;}}else if (Map.class.isAssignableFrom(clazz)){Map map = (Map) o;for (Object value : map.entrySet()){Map.Entry entry = (Map.Entry) value;return entry.getValue() instanceof MultipartFile;}}return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse|| o instanceof BindingResult;}
}
言盡于此,記得按時(shí)吃飯。社會(huì)的邊角料,老媽的小驕傲!你我都有光明的未來!