Aop 切面和本地缓存实现接口防重复请求提交
自定义注解类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 重复请求 * * @Author: * @Date: */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface NoRepeatRequest { } |
缓存配置类
这边本地缓存用的是google guava cache,缓存有效期是3秒。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.concurrent.TimeUnit; /** * @Author: * @Date: */ @Configuration public class CacheConfig { @Bean public Cache repeatCache(){ final Cache<Object, String> repeatCache = CacheBuilder.newBuilder() // cache的初始大小 .initialCapacity(20) // 并发数 .concurrencyLevel(10) // cache中的数据在写入之后的存活时间为3秒 .expireAfterWrite(3, TimeUnit.SECONDS) .build(); return repeatCache; } } |
切面类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | import cn.hutool.core.util.ArrayUtil; import com.google.common.cache.Cache; import com.ls.uem.emer.command.common.exception.CommandErrorCode; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * 防重复请求 * * @Author: * @Date: */ @Aspect @Slf4j @Component public class NoRepeatRequestAspect { @Autowired private Cache<Object, Object> repeatCache; @Pointcut("@annotation(com.sww.annotation.NoRepeatRequest)") public void noRepeat() { } @Around("noRepeat()") public Object repeatRequestCheck(ProceedingJoinPoint joinPoint) throws Throwable { Object result; Object[] args = joinPoint.getArgs(); if (ArrayUtil.isNotEmpty(args)){ Object key = args[0]; log.info("防重复请求缓存实时数量:{}", repeatCache.size()); if (repeatCache.getIfPresent(key) == null){ repeatCache.put(key, System.currentTimeMillis()); result = joinPoint.proceed(); } else{ throw new BizServiceException(ErrorCode.REPEAT_REQUEST.getDesc()); } } else{ result = joinPoint.proceed(); } return result; } } |
接口
1 2 3 4 5 6 7 8 9 10 11 | /** * * @param vo * @return */ @PostMapping("/tttt") @NoRepeatRequest public JsonResult tttt(@RequestBody @Valid TestVO vo) { commandService.save(vo); return JsonResult.success(); } |