日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

常用自定义注解

發布時間:2025/3/12 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 常用自定义注解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

導航

  • 一、方法計時器
  • 二、valid 參數校驗的通用返回
  • 三、接口訪問頻次攔截(冪等)

一、方法計時器

注解類:MethodTimer

@Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface MethodTimer { }

處理器(需要AOP和spring的支持):MethodTimerProcessor

@Slf4j @Component @Aspect public class MethodTimerProcessor {/*** 處理 @MethodTimer 注解*/@Around("@annotation(methodTimer)")public Object timerAround(ProceedingJoinPoint point, MethodTimer methodTimer) throws Throwable {long beginMills = System.currentTimeMillis();// process the methodObject result = point.proceed();log.info("{} 耗時 : {} ms", point.getSignature(), System.currentTimeMillis() - beginMills);return result;} }

使用方法:直接標記在 Controller 的方法上。

二、valid 參數校驗的通用返回

注解類:ValidCommonResp

@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ValidCommonResp { }

處理器(aop+spring):ValidCommonRespProcessor

@Slf4j @Aspect @Component public class ValidCommonRespProcessor {/*** 處理 @ValidCommonResp 注解.* 注意,BindingResult是Spring validation的校驗結果,* 當參數傳入 BindingResult后,Spring MVC就不再控制校驗* 結果的返回,如果不希望使用 @ValidCommonResp的校驗結果* 封裝,請在方法中實現校驗結果的處理,二者任選其一。** @author mouhaotian*/@Around("@annotation(validCommonResp)")public Object aroundAdvice(ProceedingJoinPoint point, ValidCommonResp validCommonResp) throws Throwable {Object[] args = point.getArgs();for (Object arg : args) {if (arg instanceof BindingResult) {BindingResult bindingResult = (BindingResult) arg;if (bindingResult.hasErrors()) {FieldError fieldError = bindingResult.getFieldError();CommonResp commonResp = new CommonResp(CommonCode.FAIL,fieldError.getField() + fieldError.getDefaultMessage());return R.data(commonResp);}break;}}Object result = point.proceed(args);return result;} }

使用方法:搭配 validation 注解、BindingResult 一起使用:

@PostMapping("/xxxx")@ValidCommonResppublic R submit(@Valid @RequestBody DoorzoneInfo doorzoneInfo, BindingResult result) {log.info("請求{}", doorzoneInfo);R commonResp = doorzoneInfoService.insertOrUpdDoorzoneInfo(doorzoneInfo);log.info("響應{}", commonResp);return commonResp;}

好處:可以替代代碼塊中處理 BindingResult 的邏輯。

三、接口訪問頻次攔截(冪等)

實現一個注解,當controller中的方法收到請求后,在一定時間之內(如10s內)拒絕接收相同參數的請求。即對后臺接口的訪問增加了頻次限制,可以理解為一種不是特別標準的冪等。

注解 @Ide

/*** 冪等校驗注解類*/ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Ide {/*** 關鍵key* key是本次請求中參數的鍵,* 重復請求的key取自header中的rid* 用來標識這個請求的唯一性* 攔截器中會使用key從請求參數中獲取value** @return String*/String key() default "";/*** 自定義key的前綴用來區分業務*/String perFix();/*** 自定義key的超時時間(基于接口)*/String expireTime();/*** 禁止重復提交的模式* 默認是全部使用*/IdeTypeEnum ideTypeEnum() default IdeTypeEnum.ALL; }

AOP 橫切處理邏輯

/*** 注解執行器 處理重復請求 和串行指定條件的請求* <p>* 兩種模式的攔截* 1.rid 是針對每一次請求的* 2.key+val 是針對相同參數請求* </p>* <p>* 另根據謝新的建議對所有參數進行加密檢驗,提供思路,可以自行擴展* DigestUtils.md5Hex(userId + "-" + request.getRequestURL().toString()+"-"+ JSON.toJSONString(request.getParameterMap()));* 或 DigestUtils.md5Hex(ip + "-" + request.getRequestURL().toString()+"-"+ JSON.toJSONString(request.getParameterMap()));* </p>*/ @Slf4j @Aspect @Component @RequiredArgsConstructor @ConditionalOnClass(RedisService.class) public class IdeAspect extends BaseAspect {private final ThreadLocal<String> PER_FIX_KEY = new ThreadLocal<String>();/*** 配置注解后 默認開啟*/private final boolean enable = true;/*** request請求頭中的key*/private final static String HEADER_RID_KEY = "RID";/*** redis中鎖的key前綴*/private static final String REDIS_KEY_PREFIX = "RID:";/*** 鎖等待時長*/private static int LOCK_WAIT_TIME = 10;private final RedisService redisService;@AutowiredIdeAspectConfig ideAspectConfig;@Pointcut("@annotation(cn.com.bmac.wolf.core.ide.annotation.Ide)")public void watchIde() {}@Before("watchIde()")public void doBefore(JoinPoint joinPoint) {Ide ide = getAnnotation(joinPoint, Ide.class);if (enable && null != ide) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();if (null == attributes) {throw new IdeException("請求數據為空");}HttpServletRequest request = attributes.getRequest();//根據配置文件中的超時時間賦值if (Func.isNotBlank(ideAspectConfig.getExpireTime())) {if(Func.isNumeric(ideAspectConfig.getExpireTime())){LOCK_WAIT_TIME = Integer.parseInt(ideAspectConfig.getExpireTime());}}//根據注解傳參賦值if(Func.isNotBlank(ide.expireTime())){LOCK_WAIT_TIME = Integer.parseInt(ide.expireTime());}//1.判斷模式if (ide.ideTypeEnum() == IdeTypeEnum.ALL || ide.ideTypeEnum() == IdeTypeEnum.RID) {//2.1.通過rid模式判斷是否屬于重復提交String rid = request.getHeader(HEADER_RID_KEY);if (Func.isNotBlank(rid)) {Boolean result = redisService.tryLock(REDIS_KEY_PREFIX + rid, LOCK_WAIT_TIME);if (!result) {throw new IdeException("命中RID重復請求");}log.debug("msg1=當前請求已成功記錄,且標記為0未處理,,{}={}", HEADER_RID_KEY, rid);} else {log.warn("msg1=header沒有rid,防重復提交功能失效,,remoteHost={}" + request.getRemoteHost());}}boolean isApiExpireTime = false;if (ide.ideTypeEnum() == IdeTypeEnum.ALL|| ide.ideTypeEnum() == IdeTypeEnum.KEY) {//2.2.通過自定義key模式判斷是否屬于重復提交String key = ide.key();if (Func.isNotBlank(key)) {String val = "";Object[] paramValues = joinPoint.getArgs();String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();//獲取自定義key的valueString[] keys = key.split("\\|");for(int i = 0; i < keys.length; i++){for (int j = 0; j < paramNames.length; j++) {//BindingResult 不能轉json,會導致線程報錯終止if (paramValues[j] instanceof BindingResult) {continue;}String params = JSON.toJSONString(paramValues[j]);if (params.startsWith("{")) {//如果是對象//通過key獲取valueJSONObject jsonObject = JSON.parseObject(params);val = val + jsonObject.getString(keys[i]);} else if (keys[i].equals(paramNames[j])) {//如果是單個k=vval = val + params;} else {//如果自定義的key,在請求參數中沒有此參數,說明非法請求log.warn("自定義的key,在請求參數中沒有此參數,防重復提交功能失效");}}}//判斷重復提交的條件String perFix = "";if (Func.isNotBlank(val)) {String[] perFixs = ide.perFix().split("\\|");int perFixsLength = perFixs.length;for(int i = 0; i < perFixs.length; i++){if(Func.isNotBlank(perFix)){perFix = perFix + ":" + perFixs[i];}else{perFix = perFixs[i];}}perFix = perFix + ":" + val;Boolean result = true;try {result = redisService.tryLock(perFix, LOCK_WAIT_TIME);} catch (Exception e) {log.error("獲取redis鎖發生異常", e);throw e;}if (!result) {String targetName = joinPoint.getTarget().getClass().getName();String methodName = joinPoint.getSignature().getName();log.error("msg1=不允許重復執行,,key={},,targetName={},,methodName={}", perFix, targetName, methodName);throw new IdeException("不允許重復提交");}//存儲在當前線程PER_FIX_KEY.set(perFix);log.info("msg1=當前請求已成功鎖定:{}", perFix);} else {log.warn("自定義的key,在請求參數中value為空,防重復提交功能失效");}}}}}@After("watchIde()")public void doAfter(JoinPoint joinPoint) throws Throwable {try {Ide ide = getAnnotation(joinPoint, Ide.class);if (enable && null != ide) {if (ide.ideTypeEnum() == IdeTypeEnum.ALL|| ide.ideTypeEnum() == IdeTypeEnum.RID) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();String rid = request.getHeader(HEADER_RID_KEY);if (Func.isNotBlank(rid)) {try {log.info("msg1=當前請求已成功處理,,rid={}", rid);} catch (Exception e) {log.error("釋放redis鎖異常", e);}}PER_FIX_KEY.remove();}if (ide.ideTypeEnum() == IdeTypeEnum.ALL|| ide.ideTypeEnum() == IdeTypeEnum.KEY) {// 自定義keyString key = ide.key();if (Func.isNotBlank(key) && Func.isNotBlank(PER_FIX_KEY.get())) {try {log.info("msg1=當前請求已成功釋放,,key={}", PER_FIX_KEY.get());PER_FIX_KEY.set(null);PER_FIX_KEY.remove();} catch (Exception e) {log.error("釋放redis鎖異常", e);}}}}} catch (Exception e) {log.error(e.getMessage(), e);}} }

其他相關類

@Data @Component @ConfigurationProperties(prefix = "ide") public class IdeAspectConfig {/*** 過期時間 秒*/private String expireTime;} @Getter @AllArgsConstructor public enum IdeTypeEnum {/*** 0+1*/ALL(0, "ALL"),/*** ruid 是針對每一次請求的*/RID(1, "RID"),/*** key+val 是針對相同參數請求*/KEY(2, "KEY");private final Integer index;private final String title; }

總結

以上是生活随笔為你收集整理的常用自定义注解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。