Java的guava 限流写法

第一步先引入 maven

复制代码
<dependency> 
 <groupId>com.google.guava</groupId> 
 <artifactId>guava</artifactId> 
 <version>32.0.1-jre</version> 
</dependency>

然后上方法

java 复制代码
private final double rateLimiter10 = 1.0 / 10.0; // 每 10 秒最多访问 1 次 005 u05 004
private final double rateLimiter20 = 1.0 / 20.0; // 每 20 秒最多访问 1 次 CFD
private final double rateLimiter30 = 1.0 / 30.0; // 每 30 秒最多访问 1 次 002
private final double rateLimiter50 = 1.0 / 50.0; // 每 50 秒最多访问 1 次 003

//这map注意一下,必须是线程安全的
private final Map<String, RateLimiter> userRateLimiters = new ConcurrentHashMap<>();

/**
 *
 * @param userId 限制的唯一码
 * @param rate 这个是执行频率
 * @return
 */
public  boolean tryAcquire(String userId,double rate) {
    userRateLimiters.putIfAbsent(userId, RateLimiter.create(rate));
    RateLimiter userRateLimiter = userRateLimiters.get(userId);
    return userRateLimiter.tryAcquire();
}

然后调用方法

java 复制代码
    @CCBMapping("/SLSCFD")
    public NotifyQueryVO notifQuery(@Valid @RequestBody NotifyQueryDTO notifyQueryDTO) {
        //唯一码是 预授信编号+查询类型
        String key = "SLSCFD"+notifyQueryDTO.getCredApprSeriNO()+"_"+notifyQueryDTO.getQueryType();
        if( tryAcquire(key,rateLimiter20)){
            return ccbBankService.notifQuery( notifyQueryDTO);
        }else{
            CommonError commonError = new CommonError();
            commonError.setCode(key);
            commonError.setValued(JsonUtils.toJSONString(notifyQueryDTO));
            commonError.setExpand("20秒/次,限流中,请稍后再试!");
            genTables.save(commonError);
            NotifyQueryVO notifyQueryVO = new NotifyQueryVO();
            notifyQueryVO.setRetCode("E0011");
            notifyQueryVO.setRetMsg("20秒/次,限流中,请稍后再试!");
            System.out.println("通知查询 SLSCFD:"+notifyQueryDTO.getCredApprSeriNO()+",20秒/次,限流中,请稍后再试!");
            return notifyQueryVO;
        }
    }

就这么简单!

相关推荐
步行cgn6 分钟前
Spring 负责注入的注解详解
java·sql·spring
摇滚侠7 分钟前
《On Java 中文版 基础卷》阅读笔记 安装 Java 和本书示例 02
java·开发语言·笔记
j7~23 分钟前
【Python】(篇六)《基础语法(函数、列表和元组、字典、文件)》---详解
开发语言·python·文件·函数·字典·编程学习·元组与列表
许彰午31 分钟前
53-审计三表
java·低代码·架构
重生之小比特35 分钟前
【C++进阶】红黑树的实现
java·开发语言·c++
程序猿乐锅40 分钟前
【黑马点评 | 第九篇】秒杀优化-异步实现
java·spring boot·redis·后端·spring·中间件·mybatis
Wx-bishekaifayuan1 小时前
springboot户外登山社交小程序19787-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·django·课程设计
FYKJ_20101 小时前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
Python图像识别2 小时前
18-【2027毕设】YOLO11烟雾检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·深度学习·yolo·毕业设计·毕设
FYKJ_20102 小时前
springboot助农产品销售商城05829-计算机课程设计、毕业设计
java·spring boot·python·mysql·spark·django