第一步先引入 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;
}
}
就这么简单!