java的Guava限流

1.导入POM依赖包

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

2.配置自定义注解

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

3.使用aop方式扫描注解

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.在controller层使用自定义注解

@RateLimitAnnotation
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值