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.01 小时前
【java入门到放弃】跨域
java·开发语言
indexsunny1 小时前
互联网大厂Java求职面试实战:微服务与Spring生态全攻略
java·数据库·spring boot·安全·微服务·面试·消息队列
沐苏瑶1 小时前
Java 搜索型数据结构全解:二叉搜索树、Map/Set 体系与哈希表
java·数据结构·算法
sg_knight2 小时前
设计模式实战:模板方法模式(Template Method)
python·设计模式·模板方法模式
FreakStudio2 小时前
ESP32居然能当 DNS 服务器用?内含NCSI欺骗和DNS劫持实现
python·单片机·嵌入式·面向对象·并行计算·电子diy
冬夜戏雪2 小时前
实习面经记录(十)
java·前端·javascript
skiy2 小时前
java与mysql连接 使用mysql-connector-java连接msql
java·开发语言·mysql
平生不喜凡桃李2 小时前
浅谈 Linux 中 namespace 相关系统调用
java·linux·服务器
乐观勇敢坚强的老彭2 小时前
2026全国青少年信息素养大赛考纲
python·数学建模
zb200641202 小时前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring