Spring Boot Lock 本地锁 防止表单重复提交

参考 https://blog.csdn.net/weixin_30808575/article/details/95788091
参考 https://www.novelweb.cn/archives/120

import java.lang.annotation.*;

//作用于方法
@Target(ElementType.METHOD)
//整个运行阶段都可见
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LocalLock {
String key() default “”;

/**
 * 过期时间 由于用的guava 暂时就忽略这个属性 集成redis时需要用到
 */
int expire() default 5;

}

package com.spring.boot.utils;

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 com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Aspect
@Configuration
public class LockMethodInterceptor {
//本地缓存
private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
//最大1000个
.maximumSize(1000)
//设置写缓存后5秒钟过期
.expireAfterAccess(5, TimeUnit.SECONDS)
.build();

@Around("execution(public * *(..)) && @annotation(com.spring.boot.utils.LocalLock)")
public Object interceptor(ProceedingJoinPoint pjp) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    LocalLock localLock = method.getAnnotation(LocalLock.class);
    String key = getKey(localLock.key(), pjp.getArgs());
    if (key != null || key != "") {
        if (CACHES.getIfPresent(key) != null) {
            throw new RuntimeException("请勿重复请求");
        }
        // 如果是第一次请求,就将 key 当前对象压入缓存中
        CACHES.put(key, key);
    }
    try {
        return pjp.proceed();
    } catch (Throwable throwable) {
        throw new RuntimeException("服务器异常");
    } finally {
        //CACHES.invalidate(key); 完成后移除key
    }
}

private String getKey(String key, Object[] args) {
    for (int i = 0; i < args.length; i++) {
        key = key.replace("arg[" + i + "]", args[i].toString());
    }
    return key;
}

}

控制层

在接口上添加@LocalLock(key = “book:arg[0]”); 意味着会将arg[0]替换成第一个参数的值,生成后的新key将被缓存起来;

package com.spring.boot.controller;

import com.spring.boot.utils.LocalLock;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/books")
public class BookController {
@LocalLock(key=“book:arg[0]”)
@GetMapping
public String query(@RequestParam String token){
return "success - " + token;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值