SpringBoot中使用防止用戶重複點擊,後臺實現

<!-- @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包,版本較低,升級下便可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章