package cn.reghao.tnb.sb.ratelimiter;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalTime;
import java.util.Arrays;

/**
 * Redis 滑动窗口限流
 *
 * @author reghao
 * @date 2025-07-15 14:23:58
 */
@Component
public class RedisZsetRateLimiter {
    private String KEY_PREFIX = "limiter_";
    private String QPS = "4";
    private StringRedisTemplate stringRedisTemplate;

    public RedisZsetRateLimiter(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void redisLuaLimiter() throws InterruptedException, IOException {
        for (int i = 0; i < 15; i++) {
            Thread.sleep(200);
            System.out.println(LocalTime.now() + " " + acquire("user1"));
        }
    }

    // 计数器限流
    public boolean acquire(String key) {
        long now = System.currentTimeMillis();
        key = KEY_PREFIX + key;
        String oldest = String.valueOf(now - 1000);
        String score = String.valueOf(now);
        String scoreValue = score;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        // lua 文件存放在 resources 目录下
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("limiter1.lua")));
        return stringRedisTemplate.execute(redisScript, Arrays.asList(key), oldest, score, QPS, scoreValue) == 1;
    }
}
