package cn.qinys.platform.gateway.limiter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.FilterArgsEvent;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.gateway.support.ConfigurationService;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Description:
 *
 * @author tanlie
 * Date: 2024/8/30 11:51
 */
@Slf4j
@Component
public class DiyRedisRateLimiter extends RedisRateLimiter {
    public DiyRedisRateLimiter(ReactiveStringRedisTemplate redisTemplate, RedisScript<List<Long>> script, ConfigurationService configurationService) {
        super(redisTemplate, script, configurationService);
    }

    private final String KEY_RESOLVER_KEY = "key-resolver";

    @Override
    public void onApplicationEvent(FilterArgsEvent event) {
        Map<String, Object> args = event.getArgs();
        if (args.containsKey(KEY_RESOLVER_KEY)) {
            String routeId = event.getRouteId() + args.get(KEY_RESOLVER_KEY).hashCode();
            log.debug("MultiRedisRateLimiter::routeId={}", routeId);
            super.onApplicationEvent(new FilterArgsEvent(event.getSource(), routeId, args));
        }
        super.onApplicationEvent(event);
    }
}
