guava 对接口限流处理

  1. 引入依赖
xml 复制代码
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>31.1-jre</version>
</dependency>
  1. 自定义注解
java 复制代码
/**
 * 限流器注解
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Limiter {
    int count() default 20;
    int time() default 1;
}
  1. 定义切面
java 复制代码
@Aspect
@Component
public class RateLimiterAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(RateLimiterAspect.class);
    private ConcurrentHashMap<String, RateLimiter> RATE_LIMITER = new ConcurrentHashMap<>();

    @Before(value = "@annotation(com.shi.demo.annotation.Limiter)")
    public void handleRateLimiter(JoinPoint jp) {
        RateLimiter rateLimiter = null;
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        Limiter annotation = method.getAnnotation(Limiter.class);
        int count = annotation.count();
        int time = annotation.time();
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        String key = className + "." + methodName;
        if (!RATE_LIMITER.containsKey(key)) {
            rateLimiter = RateLimiter.create(count, time, TimeUnit.SECONDS);
            RATE_LIMITER.put(key, rateLimiter);
        }
        rateLimiter = RATE_LIMITER.get(key);
        if (!rateLimiter.tryAcquire()) {
            throw new RuntimeException("限流了,请稍后再试");
        }
    }
}
  1. 接口上 使用注解
java 复制代码
@RestController
@RequestMapping("/users")
public class UserController {

	@Limiter
    @GetMapping
    public String get(){
        return "get";
    }

	@Limiter(count=20,time=1)
    @PostMapping
    public String post(){
        return "post";
    }

    @DeleteMapping
    public String delete(){
        return "delete";
    }
}
相关推荐
hstar952710 分钟前
二、即时通讯系统设计经验
java·架构
菥菥爱嘻嘻17 分钟前
JS手写代码篇---手写ajax
开发语言·javascript·ajax
江梦寻23 分钟前
MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)
开发语言·后端·python·macos·架构·策略模式
霖檬ing26 分钟前
Python——MySQL远程控制
开发语言·python·mysql
风象南30 分钟前
SpringBoot的4种死信队列处理方式
java·spring boot·后端
互联网全栈架构1 小时前
遨游Spring AI:第一盘菜Hello World
java·人工智能·后端·spring
qq_429879672 小时前
省略号和可变参数模板
开发语言·c++·算法
优秀的颜2 小时前
计算机基础知识(第五篇)
java·开发语言·分布式
BillKu2 小时前
Java严格模式withResolverStyle解析日期错误及解决方案
java
CodeWithMe2 小时前
【C/C++】std::vector成员函数清单
开发语言·c++