Java's Guava current limiting

1. Import the POM dependency package

<!--Guava限流-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
</dependency>

2. Configure custom annotations

@Inherited
@Documented
@Target({
    
    ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitAnnotation {
    
    
}

3. Use aop to scan annotations

package cn.sms.aop;
import cn.sms.core.security.Result;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Date;

/**
 * @Author
 * @Date 2023/4/17 19:55
 * @Description: TODO
 * @Version 1.0
 */
@Aspect
@Component
public class RateLimitAop {
    
    
    //限流每秒1次。如果设置为n,则每秒限流为1/n
    private RateLimiter rateLimiter= RateLimiter.create(1);
    @Pointcut(value = "@annotation(cn.sms.aop.RateLimitAnnotation)")
    public void rateLimit(){
    
    
    }
    @Around("rateLimit()")
    public Result around() {
    
    
        Boolean flag = rateLimiter.tryAcquire();
        if (!flag) {
    
    
            return Result.error(new Timestamp(new Date().getTime()).toString()+"限流");
        }
        return Result.success();
    }
}

4. Use custom annotations in the controller layer

@RateLimitAnnotation

Guess you like

Origin blog.csdn.net/SmileSunshines/article/details/130295619