Springboot自定义注解

一、引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

二、定义一个标识注解

//@Inherited  //说明子类可以继承父类中的该注解
@Documented //说明注解将被包含在javadoc中
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})  //定义注解的作用目标:方法、属性、类
@Retention(RetentionPolicy.RUNTIME)  //定义注解的保留策略:注解会在class字节码文件中存在,在运行时可以通过反射获取到
public @interface RateLimitAspect {

}

 

三、使用切面

@Component
@Aspect
public class RateLimitAop {

    @Autowired
    private HttpServletResponse response;

    private RateLimiter rateLimiter = RateLimiter.create(4.0); //比如说,我这里设置"并发数"为5

    @Pointcut("@annotation(com.uniview.RateLimiter.RateLimitAspect)")
    public void serviceLimit(){}

    @Around("serviceLimit()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Boolean flag = rateLimiter.tryAcquire();
        Object obj = null;
        new Thread(() -> {
            try {
                TimeUnit.MILLISECONDS.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        try {
            if (flag) {
                output(response, "OK");
                obj = joinPoint.proceed();
            }else{
//                String result = JSONObject.fromObject(BaseResult.build(ErrorCode.NOMESSAGE, "failure")).toString();
                String result = "失败";
                output(response, result);

            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        System.out.println("flag=" + flag + ",obj=" + obj);
        return obj;
    }

    public void output(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(msg.getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }
}

四、测试

@RequestMapping("/")
@RestController
public class Test {

//    RateLimiter rateLimiter = RateLimiter.create(1.0);

    @RequestMapping("/test")
    @RateLimitAspect
    public void test() {
//        System.out.println(rateLimiter.acquire());
        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
        String format1 = format.format(System.currentTimeMillis());
        System.out.println(format1);
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值