package com.liquidnet.commons.lang.util.spring;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author AnJiabin <anjiabin@zhengzai.tv>
 * @version V1.0
 * @Description: TODO
 * @class: RestTemplateOkConfig
 * @Package com.liquidnet.commons.lang.util.spring
 * @Copyright: LightNet @ Copyright (c) 2022
 * @date 2022/6/9 11:56
 */
public class RestTemplateOkConfig {
    private static RestTemplate restTemplate;

    static{
        long startTime = System.currentTimeMillis();
        ConnectionPool pool = new ConnectionPool(500, 5, TimeUnit.MINUTES);

        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectionPool(pool)
                .connectTimeout(2, TimeUnit.MINUTES)
                .readTimeout(2, TimeUnit.MINUTES)
                .writeTimeout(2, TimeUnit.MINUTES)
                .hostnameVerifier((hostname, session) -> true)
                // 设置代理
//              .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
                // 拦截器
//                .addInterceptor()
                .build();
        ClientHttpRequestFactory factory = new OkHttp3ClientHttpRequestFactory(okHttpClient);

        restTemplate = new RestTemplate(factory);
        System.out.println("初始化 RestTemplate，bean name :{}"+"restTemplate");
        System.out.println("初始化 ok RestTemplate总耗时"+(System.currentTimeMillis()-startTime));

    }

    public static RestTemplate getRestTemplate(){
        return restTemplate;
    }

    private static int getMaxCpuCore(){
        int cpuCore = Runtime.getRuntime().availableProcessors();
        return  cpuCore;
    }
}
