java通过AOP实现接口访问次数

发布时间:2026/6/28 4:13:48
java通过AOP实现接口访问次数 1、首先创建一个注解Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) Documented public interface InvocationCount { int count() default 2; }2、编写切面类需要用到redisAspect Component public class InvocationCountAspect { /** * 用户导出次数 key 前缀 */ private static final String PREFIX invocation_count:; Resource private RedisCache redisService; Around(annotation(invocationCount)) public Object around(ProceedingJoinPoint joinPoint, InvocationCount invocationCount) throws Throwable { // 方法执行前判断是否超过次数 Long userId SecurityUtils.getUserId(); int allCount invocationCount.count(); Integer useCount 0; String url StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 64); String key PREFIX userId : url; if (redisService.hasKey(key)) { useCount redisService.getCacheObject(key); if (useCount allCount) { throw new ServiceException(使用次数已达上限请六个小时后再试); } } Object proceed joinPoint.proceed(); // 方法执行后更新次数 redisService.setCacheObject(key, useCount, 6, TimeUnit.HOURS); return proceed; } }这里时间固定为六个小时可以自行在注解中添加Integer类型的字段实现时间自定义3、使用示例/** * count 1 代表指定时间内只能访问一次 */ InvocationCount(count 1) public AjaxResult test(){ System.out.println(测试接口是否受限制); return success(); }