<!-- @Aspect需要的包 -->
<!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
/**
* @author
* @date 2020-03-23 10:01
* @Description: 自定义一个注解类,将来用在禁止重复提交的方法上
*/
public @interface Commit {
String name() default "name:";
}
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.skyedu.toker.annotation.Commit;
import com.skyedu.toker.common.RespBean;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
/**
* @author
* @date 2020-03-23 10:02
* @Description: 自定义一个切面类,利用aspect实现切入所有方法
*/
@Aspect
@Configuration
public class SubmitAspect {
private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
// 最大缓存 100 个
.maximumSize(100)
// 设置缓存过期时间为S
.expireAfterWrite(3, TimeUnit.SECONDS)
.build();
@Around("execution(public * *(..)) && @annotation(com.annotation.Commit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Commit form= method.getAnnotation(Commit.class);
String key = getCacheKey(method, pjp.getArgs());
if (!StringUtils.isEmpty(key)) {
if (CACHES.getIfPresent(key) != null) {
RespBean resultResponse = new RespBean();
resultResponse.setData(null);
resultResponse.setMsg("请勿重复请求");
resultResponse.setCode(405);
return resultResponse;
}
// 如果是第一次请求,就将key存入缓存中
CACHES.put(key, key);
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("服务器异常");
} finally {
CACHES.invalidate(key);
}
}
/**
*将来还要加上用户的唯一标识
*/
private String getCacheKey(Method method,Object[] args) {
return method.getName() + args[0];
}
}
@RequestMapping("/test")
@Commit
public String test() {
return ("程序逻辑返回");
}
org.aspectj.apache.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 18 异常
pom文件中 aspectjweaver jar包,版本较低,升级下便可。