1:访问时间限制
package com.amdox.common.annotation; import java.lang.annotation.*; /** * 此类应用在方法上面 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LimitUseTime{ /** * 可以写方法名称:描述 * @return */ String channel() default "backstage"; /** * 多次时间重复提交,提示 * @return */ int expireTime() default 3; }
2:具体实现的类(根据spring MVC aop 和redis来实现)
package com.amdox.common.annotation; import cn.hutool.core.util.StrUtil; import com.amdox.common.vo.Msg; import lombok.extern.slf4j.Slf4j; 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.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; /** * 避免出现重复提交数据 */ @Component @Aspect @Slf4j public class CheckRepeatCommitAspect { @Autowired @Qualifier("stringRedisTemplate") private RedisTemplate<String, String> redisTemplate; @Pointcut("@annotation(com.amdox.common.annotation.LimitUseTime)") private void checkRepeatCommit() { } @Around("checkRepeatCommit()") public Object checkRepeatCommit(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); String bizKey=""; Object[] args=joinPoint.getArgs(); if(args!=null&& args.length>0) { bizKey=method.getName() + args[0]; }else { bizKey=method.getName(); } // 获取当前请求方法的注解,根据注解配置获取参数 LimitUseTime limitUseTime= method.getAnnotation(LimitUseTime.class); if (limitUseTime!= null) { //注解上的描述 String channel = limitUseTime.channel(); //时长 int expireTime = limitUseTime.expireTime(); //查询redis是否有数据 String key = getRepeatCommitLock(channel, method.getName(), bizKey, expireTime); if (StringUtils.isBlank(key)) { return new Msg<>().fail(expireTime+"秒!请勿重复提交数据"); } } return joinPoint.proceed(); } public String getRepeatCommitLock(String channel, String module, String bizKey, int expireTime) { if (StringUtils.isEmpty(module) || StringUtils.isEmpty(bizKey)) { return null; } String redisKey = channel + StrUtil.COLON + bizKey ; long count = redisTemplate.opsForValue().increment(redisKey, 1); if (count == 1) { redisTemplate.expire(redisKey, expireTime==0?10:expireTime, TimeUnit.SECONDS); return redisKey; } else { return null; } } }
3:应用场景 expireTime限制时间,不填默认3秒
@LimitUseTime(channel = "CloudBrandPoster",expireTime = 3)
public Msg insert(@RequestBody CloudBrandPoster template) {
return success();
}