springboot实现自定义注解

1:引入jar包



    org.springframework.boot
    spring-boot-starter-aop

2:定义自定义注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
    //访问次数
    int count() default 2;
    //单位分钟
    int time() default 5;
}

3:添加切面,定义切点

 
  
@Aspect
@Component
public class RequestLimitContract {

    @Autowired
    private JedisTemplate jedisTemplate;

    @Pointcut("@annotation(com.mryx.gus.annotation.RequestLimit)")
    public void annotationPointCut() {
    }

    @Before("annotationPointCut()")
    public Object before(JoinPoint joinPoint) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String comCode = request.getParameterMap().get("com_code")[0];
        if (StringUtils.isEmpty(comCode)) {
            request.setAttribute("success", false);
            request.setAttribute("message", "货主为空");
            return ResponseDto.createFailureResponse("货主为空");
        }
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        RequestLimit annotation = method.getAnnotation(RequestLimit.class);

        String count = jedisTemplate.get(comCode);
        Integer timeout;
        if (StringUtils.isEmpty(count)) {
            jedisTemplate.setex(comCode, "1", annotation.time() * 60);
        } else {
            Integer num = Integer.valueOf(count);
            if (num == annotation.count()) {
                request.setAttribute("success", false);
                request.setAttribute("message", "超出访问上线");
                return ResponseDto.createFailureResponse("超出访问上线");
            }
            timeout = jedisTemplate.ttl(comCode);
            jedisTemplate.setex(comCode, String.valueOf(Integer.valueOf(count) + 1), timeout);
        }
        request.setAttribute("success", true);
        request.setAttribute("message", "成功");
        return ResponseDto.createSuccessResponse("成功");
    }


}

4:定义Controller

@RestController
@RequestMapping("url")
public class URLController {

    
@RequestLimit(count = 2,time = 5)
@RequestMapping( "/test") public String test( @PathVariable( "user") User user,HttpServletRequest request) { return " 成功 :" + name ; }}

5:http://localhost:8080/url/test/xiaoming

直接访问就OK


你可能感兴趣的:(技术分享)