package com.ruoyi.lsfx.config;

import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置（使用连接池优化性能）
 */
@Configuration
public class RestTemplateConfig {

    @Value("${lsfx.api.connection-timeout:30000}")
    private int connectionTimeout;

    @Value("${lsfx.api.read-timeout:60000}")
    private int readTimeout;

    @Value("${lsfx.api.pool.max-total:100}")
    private int maxTotal;

    @Value("${lsfx.api.pool.default-max-per-route:20}")
    private int defaultMaxPerRoute;

    @Bean
    public RestTemplate restTemplate() {
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(maxTotal); // 最大连接数
        connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute); // 每个路由的最大连接数

        // 创建HttpClient并设置连接池
        HttpClient httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .build();

        // 创建HttpComponentsClientHttpRequestFactory
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        factory.setConnectTimeout(connectionTimeout);
        factory.setConnectionRequestTimeout(connectionTimeout);

        return new RestTemplate(factory);
    }
}
