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";
    }
}
相关推荐
w2sfot29 分钟前
Passing Arguments as an Object in JavaScript
开发语言·javascript·ecmascript
郝学胜-神的一滴44 分钟前
避免使用非const全局变量:C++中的最佳实践 (C++ Core Guidelines)
开发语言·c++·程序人生
我没想到原来他们都是一堆坏人1 小时前
(未完待续...)如何编写一个用于构建python web项目镜像的dockerfile文件
java·前端·python
搞一搞汽车电子1 小时前
S32K3平台eMIOS 应用说明
开发语言·驱动开发·笔记·单片机·嵌入式硬件·汽车
沙二原住民1 小时前
提升数据库性能的秘密武器:深入解析慢查询、连接池与Druid监控
java·数据库·oracle
Jerry&Grj1 小时前
SpringBoot埋点功能技术实现方案深度解析:架构设计、性能优化与扩展性实践
java·微服务·性能优化·springboot·架构设计·埋点技术
没有bug.的程序员1 小时前
Redis Stream:轻量级消息队列深度解析
java·数据库·chrome·redis·消息队列
总有刁民想爱朕ha2 小时前
车牌模拟生成器:Python3.8+Opencv代码实现与商业应用前景(C#、python 开发包SDK)
开发语言·python·数据挖掘
用户8160791833332 小时前
告别“魔法”:包你解决 Gradle 的下载慢问题
java
小菜全2 小时前
uniapp新增页面及跳转配置方法
开发语言·前端·javascript·vue.js·前端框架