package cn.reghao.tnb.gateway.limiter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @author reghao
 * @date 2024-11-21 17:10:03
 */
public class GlobalLimiterFilter implements GlobalFilter, Ordered {
    private final RedisTemplate<String, String> redisTemplate;
    private MyRateLimiter myRateLimiter;

    public GlobalLimiterFilter(RedisTemplate<String, String> redisTemplate, MyRateLimiter myRateLimiter) {
        this.redisTemplate = redisTemplate;
        this.myRateLimiter = myRateLimiter;
    }

    @Override
    public int getOrder() {
        return -1;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取到调用客户端的IP地址
        String ip = exchange.getRequest().getRemoteAddress().getHostName();
        //从数据库中获取到该IP地址对应的限流参数
        /*IpRate ipRate = ipRateService.get(ip);
        String path = exchange.getRequest().getPath().value();

        //如果允许同行，没有超过该ip的流量限制
        if(myRateLimiter.isAllowed(ip, path)){
            return chain.filter(exchange);
        }else{
            exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
            return exchange.getResponse().setComplete();
        }*/

        return chain.filter(exchange);
    }
}
