package cn.qinys.platform.gateway.config;


import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 网关限流配置类
 *
 * @author tanlie
 * @date 2024-8-30
 */
@Configuration
public class RequestRateLimitConfiguration {

    /**
     * ip地址限流
     *
     * @return 限流key
     */
    @Bean
    @Primary
    public KeyResolver remoteAddressKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress());
    }

    /**
     * 请求路径限流
     *
     * @return 限流key
     */
    @Bean
    public KeyResolver apiKeyResolver() {
        return exchange -> {
            String token = exchange.getRequest().getHeaders().getFirst("Authorization");
            if (!StringUtils.hasLength(token)) {
                token = UUID.randomUUID().toString().replaceAll("-", "");
            }
            String routeId = exchange.getRequest().getURI().getPath() + "-" + token;
            return Mono.just(routeId);
        };
    }
}
