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;
        }
    }

就这么简单!

相关推荐
IT小盘5 小时前
03-大模型API不只是发送Prompt-流式输出超时重试与异常处理
人工智能·python·prompt
Zzz不能停7 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试
小Ti客栈7 小时前
Spring Boot 集成 Springdoc-OpenAPI 与 Knife4j实现接口文档与可视化调试
java·spring boot·后端
互联网中的一颗神经元8 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Ai拆代码的曹操8 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
郭老二8 小时前
【Python】常用模块:xmlrpc
python
动恰客流统计9 小时前
ReID边缘计算视觉统计:餐饮店客流增长的数字化破局路径
java·大数据·运维·人工智能
名字还没想好☜9 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
Ivanqhz9 小时前
Rust &‘static str浅析
java·前端·javascript·rust
威联通网络存储9 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造