一、引入依赖
<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);