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

就这么简单!

相关推荐
MY_TEUCK1 天前
【2026最新Python+AI学习基础】Python 入门笔记篇
笔记·python·学习
2401_833269301 天前
Java网络编程入门
java·开发语言
金銀銅鐵1 天前
[Java] 如何将 Lambda 表达式对应的类保存到 class 文件中?
java·后端
赢乐1 天前
大模型学习笔记:检索增强生成(RAG)架构
人工智能·python·深度学习·机器学习·智能体·幻觉·检索增强生成(rag)
それども1 天前
Gradle 构建疑难杂症 Could not find netty-transport-native-epoll-linux-aarch_64.ja
java·服务器·gradle·maven
正儿八经的少年1 天前
application.yml 系列配置文件作用与区别
java·配置文件
鱼很腾apoc1 天前
【学习篇】第20期 超详解 C++ 多态:从语法规则到底层原理
java·c语言·开发语言·c++·学习·算法·青少年编程
浪里行舟1 天前
你的品牌正在被AI“遗忘”?用BuildSOM找回搜索的下一个风口
人工智能·python·程序员
cheems95271 天前
[Spring MVC] 统一功能与拦截器实践总结
java·spring·mvc
Full Stack Developme1 天前
Spring Boot 事务管理完整教程
java·数据库·spring boot