Guava 包的 RateLimiter 限流 -- 支持nacos动态读参数,接口独立注解

Java服务接口层面限流

参考:https://www.cnblogs.com/myseries/p/12634557.html

https://my.oschina.net/u/3768341/blog/3054276

方案

核心思路是使用Guava 包的 RateLimiter 做限流

结合aop使用注解打到接口上 改参数即可实现每个接口独立控制限流次数

per.times.xxx 即 QPS,设置多少就是每秒最大不超过次数

@RequestMapping("/testAnnotation")
@AopRateLimit(configKey = "${per.times.testAnnotation}")
public String testAnnotation() {
  return "success";
}

@AopRateLimit(configKey = “${per.times.testAnnotation}”)

per.times.testAnnotation 这里是外部化配置(从nacos读取参数),做到不需要重启的热部署,各接口独立
在这里插入图片描述
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HpMKqTzG-1631512914894)(https://i.loli.net/2021/09/13/yS8KcZH36hO2kRM.png)]

当接口QPS大于1的时候就会返回 “服务器繁忙,请稍后再试!”

自测多次,10个请求 1个会成功,其余被拦截,返回自定义提示。


以下为使用 Jmeter压测进行 10个并发测试请求

image-20210909161014450.png

image-20210909161027276.png

image-20210909161206157.png

自定义注解:

package com.yww.common.annotation;

import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Akizora
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AopRateLimit {
    /**
     * 读取 nacos 配置的外部化参数
     *
     * @return
     */
    String configKey() default "";

    /**
     * 默认空字符串
     *
     * @return
     */
    String value() default "";

    /**
     * 每秒向桶中放入令牌的数量 默认最大即不做限流
     *
     * @return
     */
    double perSecond() default Double.MAX_VALUE;

    /**
     * 获取令牌的等待时间 默认500
     *
     * @return
     */
    int timeOut() default 500;

    /**
     * 超时时间单位
     *
     * @return
     */
    TimeUnit timeOutUnit() default TimeUnit.MILLISECONDS;
}

aop切面:

package com.yww.action.web.aop;

import com.google.common.util.concurrent.RateLimiter;
import com.yww.common.annotation.AopRateLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;

import java.lang.reflect.Method;

/**
 * 使用guava包的 rateLimiter 实现的令牌桶限流,支持各接口独立配置限流参数
 *
 * @author dzc
 */
@SuppressWarnings("all")
@Aspect
@Component
public class AopRateLimitAspect {
    @Autowired
    private ConfigurableEnvironment environment;

    private final static Logger logger = LoggerFactory.getLogger(AopRateLimitAspect.class);

    private final RateLimiter rateLimiter = RateLimiter.create(Double.MAX_VALUE);

    /**
     * 定义切点
     * 1、通过扫包切入
     * 2、带有指定注解切入
     */
    @Pointcut("@annotation(com.yww.common.annotation.AopRateLimit)")
    public void checkPointcut() {
    }

    @ResponseBody
    @Around(value = "checkPointcut()")
    public Object aroundNotice(ProceedingJoinPoint pjp) throws Throwable {
        logger.info("拦截到了{}方法...", pjp.getSignature().getName());
        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //获取目标方法
        Method targetMethod = methodSignature.getMethod();
        if (targetMethod.isAnnotationPresent(AopRateLimit.class)) {
            //获取目标方法的@AopRateLimit注解
            AopRateLimit AopRateLimit = targetMethod.getAnnotation(AopRateLimit.class);
            //从环境变量中获取
            String perSecond = environment.resolvePlaceholders(String.valueOf(AopRateLimit.configKey()));
            logger.info("AopRateLimit configKey,{}", perSecond);
            rateLimiter.setRate(Double.valueOf(perSecond));
            if (!rateLimiter.tryAcquire(AopRateLimit.timeOut(), AopRateLimit.timeOutUnit())) {
                return "服务器繁忙,请稍后再试!";
            }
        }
        return pjp.proceed();
    }
}

Aop 核心代码

  1. 从容器上下文中获取外部化配置参数
  2. 使用RateLimiter的tryAcquire令牌桶算法实现限流

同时nacos配置中心已集成好,

在 framework 项目引入 config 依赖,

spring-cloud-starter-alibaba-nacos-config

并在bootstrap.properties里加入配置

#nacos做配置中心
spring.cloud.nacos.config.server-addr=192.168.161.251:8848
#配置使得nacos支持properties读取值
spring.cloud.nacos.config.file-extension=properties
spring.cloud.nacos.config.group=DEFAULT_GROUP

最后在 nacos 界面新增不同环境(dev,test,prod独立配置,可以通过Group设置)的配置文件,将原来项目中的 application-test.properties 文件复制迁移。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值