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

就这么简单!

相关推荐
珍珠先生2 分钟前
第10章 JDK 17 新特性:语法糖与新能力
java
Rnan-prince5 分钟前
堆与TopK · 从零到通透 —— 9 节全系列复盘
python·算法
吴声子夜歌1 小时前
ApacheCommons——commons-text(模板替换与文本算法)
java·开发语言·算法·apache
Haooog1 小时前
Agent 开发中的 Memory:State、短期记忆、长期记忆与 Memory Retrieval
java·agent·memory
2601_962294611 小时前
Python接口自动化测试实战:使用requests库
python·接口自动化测试·异常处理·requests库·api测试
砚底藏山河1 小时前
【量化纯GET实战 #23】多股票相关性:用收益率看板块联动
java·数据库·python·金融·数据分析
阿童木写作1 小时前
跨境电商翻译工具推荐:批量图片翻译+视频字幕实时翻译
人工智能·python·音视频
晶捷软件1 小时前
晶捷智能:集团型制造企业ERP如何实现多工厂统一管控
大数据·人工智能·python·制造
抠脚小弟2 小时前
Spring Cache 使用详解:从入门到实战
java·spring
oyguyteggytrrwwwrt2 小时前
闵可夫斯基差演示
python