java springboot接口限流实现
通过redis实现,一秒内同一个用户,限制请求一次
    // 限流逻辑
        String rateLimitKey = RATE_LIMIT_KEY_PREFIX + userImageUrl;
        Boolean isLimited = stringRedisTemplate.opsForValue().setIfAbsent(rateLimitKey, "1", 1, TimeUnit.SECONDS);
        if (isLimited == null || !isLimited) {
            logger.warn("User {} is submitting too frequently. Request rejected.", userImageUrl);
            throw new RuntimeException("You can only submit once every second.");
        }
解释
限流逻辑:
String rateLimitKey = RATE_LIMIT_KEY_PREFIX + userImageUrl;:生成一个唯一的 Redis 键,用于标识用户的限流状态。
Boolean isLimited = stringRedisTemplate.opsForValue().setIfAbsent(rateLimitKey, "1", 1, TimeUnit.SECONDS);:使用 setIfAbsent 方法设置键值对,如果键已经存在则返回 false,否则返回 true 并设置键的过期时间为 1 秒。
if (isLimited == null || !isLimited):如果 isLimited 为 false,说明用户已经在一秒内提交过请求,拒绝该请求并抛出异常。
日志记录:
使用 logger.warn 记录被限流的请求,便于调试和监控。
其他操作:
生成作品数据、设置 Redis 状态、将参数放入缓存、将任务放入队列等操作保持不变。
通过这种方式,可以确保在一秒内同一个用户只能提交一次请求,从而避免频繁提交导致的并发问题。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号