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";
    }
}
相关推荐
知识分享小能手几秒前
R语言入门学习教程,从入门到精通,R语言入门(3)
开发语言·学习·r语言
AI人工智能+电脑小能手1 分钟前
【大白话说Java面试题 第41题】【JVM篇】第1题:JVM由哪些部分组成?
java·开发语言·jvm·后端·面试
0xDevNull3 分钟前
ConcurrentHashMap 与 Hashtable 深度对比
java·开发语言
happymaker06264 分钟前
Spring学习日记——Day01(简单配置使用Spring,手写Spring的简单工厂模式)
java·学习·spring
木易 士心5 分钟前
深度解析:一个 Java 对象究竟占用多少字节?
java·开发语言·后端
夜猫子ing6 分钟前
《嵌入式 Linux 控制服务从零搭建(二):从目录结构到 CMakeLists,搭一个像样的 C++ 工程骨架》
java·前端·c++
人道领域1 小时前
【LeetCode刷题日记】二叉树翻转:递归与迭代全解析
java·算法·leetcode
Cyan_RA91 小时前
SpringMVC 视图和视图解析器 万字详解
java·spring·mvc·springmvc·请求重定向·modelandview·视图解析器
水云桐程序员8 小时前
C++可以写手机应用吗
开发语言·c++·智能手机
测试员周周8 小时前
【AI测试智能体】为什么传统测试方法对智能体失效?
开发语言·人工智能·python·功能测试·测试工具·单元测试·测试用例