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";
    }
}
相关推荐
REDcker2 分钟前
Android 15 16KB 内存页适配详解
android·开发语言·python
2zcode2 分钟前
基于MATLAB同态滤波的医学图像增强系统设计与实现
开发语言·计算机视觉·matlab
脏脏a2 分钟前
飞牛NAS部署EasyNVR实操:摄像头RTSP接入、本地录像与公网回看
开发语言·php
杰佛史彦明116 分钟前
PDF 表格转 CSV:Python 实现方法与代码解析
开发语言·python·pdf
gugucoding21 分钟前
39. 【C语言】经典 C 项目实战:迷你 HTTP 服务器
c语言·开发语言·http
.Cnn25 分钟前
Redis基础day02
java·数据库·redis
能有时光27 分钟前
[MAF的Agent管道详解-07]利用AIAgent中间件构建Agent管道
java·数据库
什巳30 分钟前
JAVA练习277- 找到字符串中所有字母异位
java·开发语言·算法·leetcode
我登哥MVP39 分钟前
HDFS硬核拆解-读写Pipeline与Java实战
java·hadoop·hdfs·云原生·云计算
头茬韭菜41 分钟前
3.6 依赖注入 — 四个依赖的精准边界
开发语言·ai·ecmascript