SpringBoot项目,限制方法只能有一个人操作

限制操作人的操作,在调用方法没有返回结果之前,其他人不能调用该方法

整体解决思路:
利用注解方式,在方法上增加注解,然后利用@Aspect切面注解给增加的注解添加面向切面类,在调用方法前,查看方法是否在调用,如果没有就增加上限制,调用方法结束,放开限制。
下面展示一些 示例代码

// 注解类
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SoloExection {
    String value() ;
}
// 切面类
@Aspect
@Component
@Slf4j
public class SoloExecutionAspect {
    //缓存2分钟
    final static long LIVE_TIME =2*60;
	
	//这里的限制用redis实现
    @Autowired
    CacheService cacheService;
    @Around("@annotation(***(包路径).SoloExection)")
    public Object aroundMethod(ProceedingJoinPoint jp) throws Throwable {
        Object result = null;
        String key = null;
        MethodSignature methodSignature = (MethodSignature)jp.getSignature();
        Method method = methodSignature.getMethod();
        SoloExection annotation = method.getAnnotation(SoloExection.class);
        key = annotation.value();
        if(!StringUtils.isEmpty(key) && cacheService.hasKey(key)){
            log.info(" Sole执行的方法{}正在执行",key);
            throw new HadesNoStackRuntimeException("该方法正在执行,请稍后再操作");
        }else {
            try {
                cacheService.put(key, JsonUtil.bean2Json(key), LIVE_TIME);
                result = jp.proceed();
                moveKey(key);
            } catch (Throwable e) {
                result = "error";
                log.error(" Solo执行的方法出错" + e);
                moveKey(key);
                throw e;
            }
        }
        return result;
    }

    public void moveKey(String key){
        if (!StringUtils.isEmpty(key) && cacheService.hasKey(key)) {
            cacheService.remove(key);
        }
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值