public class ChaIntercept {
@Autowired
protected MasterUrlService masterUrlService;
@Resource
private ChaMapper chaMapper;
static String CHANNEL_COMPARISON_PREFIX = "COMPARISON_PREFIX_";
@Resource
private RedisTemplate<String, Integer> redisTemplate;
@Around("@annotation(com.annotation.RequestLimitRate)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
log.debug("进入撞库接口调用-开始获取令牌");
CheckModel reqDto = JSONObject.toJavaObject(
JSONObject.parseObject(JSONObject.toJSONString(joinPoint.getArgs()[0])), CheckModel.class);
if (reqDto != null) {
Channel channel = chaMapper.selectByNo(reqDto.getNo());
if (channel == null) {
throw new InternalException("获取令牌,未找到渠道信息");
}
if (channel.getComparisonSwitch() == 0) {
throw new InternalException(
"获取令牌,渠道已被禁止调用撞库接口,渠道ID={" + channel.getId() + "},渠道name={" + channel.getChannelName() + "}");
}
if (channel.getPermitsPerSecond() != null) {
// key作用:不同的接口,不同的流量控制
String permitsKey = CHANNEL_COMPARISON_PREFIX + channel.getId();
Long permitsThreshold = redisTemplate.opsForValue().increment(permitsKey);
// 验证缓存是否有命中key
if (permitsThreshold == null || permitsThreshold > channel.getPermitsPerSecond()) {
log.info("令牌桶={},第{}次获取令牌失败", permitsKey, permitsThreshold);
throw new InternalException("请求频率过高,请稍后重试!");
} else {
log.info("令牌桶={},第{}次获取令牌成功", permitsKey, permitsThreshold);
if (permitsThreshold != null && permitsThreshold == 1) {
redisTemplate.expire(permitsKey, 1, TimeUnit.SECONDS);
}
}
}
}
return joinPoint.proceed();
}
}