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";
    }
}
相关推荐
技术卷1 分钟前
GO网络编程(一):基础知识
开发语言·网络·golang
不惑_2 分钟前
Redission · 可重入锁(Reentrant Lock)
java·redis·分布式·spring
ziyue75759 分钟前
java将word转pdf
java·pdf·word
努力编程的阿伟10 分钟前
Java多态性:面向对象编程的精髓
java·开发语言
小布-0114 分钟前
Spring BeanUtils.copyProperties实现机制
java·后端·spring
地球空间-技术小鱼17 分钟前
SQL常用语法
java·开发语言·前端
费曼乐园37 分钟前
在 Spring 中不能将 @Value 注解应用于 static 字段的原因
java·spring
一般路过糸.39 分钟前
一文了解构建工具——Maven与Gradle的区别
java·maven
橘子海全栈攻城狮40 分钟前
【源码+文档+调试讲解】交通信息管理系统
运维·开发语言·数据库·python·sqlite
BIGSHU092342 分钟前
Spring Web是个什么东西
java·前端·spring