分布式环境 如何进行限流

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

}
 

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值