RestClientConfig.java 1.9 KB
package vion.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.DefaultUriBuilderFactory;

import java.net.http.HttpClient;
import java.time.Duration;
import java.util.concurrent.Executors;

/**
 * @author vion
 * @date 2024/7/19
 */
@Configuration
@Slf4j
public class RestClientConfig {

    @Bean(name = "bongRestClient")
    public RestClient getBongRestClient() {
        return RestClient.builder()
                .baseUrl("https://proapi.xbongbong.com")
                .requestFactory(new JdkClientHttpRequestFactory(httpClient()))
                .build();
    }

    @Bean(name = "oDingRestClient")
    public RestClient getODingRestClient() {
        // disable url encoding
        // 在对 + 号进行处理时,默认对该字符不处理
        var uriBuilderFactory = new DefaultUriBuilderFactory("https://oapi.dingtalk.com");
        uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
        return RestClient.builder()
                .uriBuilderFactory(uriBuilderFactory)
                .requestFactory(new JdkClientHttpRequestFactory(httpClient()))
                .build();
    }

    @Bean(name = "dingRestClient")
    public RestClient getdingRestClient() {
        return RestClient.builder()
                .baseUrl("https://api.dingtalk.com")
                .requestFactory(new JdkClientHttpRequestFactory(httpClient()))
                .build();
    }

    private HttpClient httpClient() {
        return HttpClient.newBuilder()
                .executor(Executors.newVirtualThreadPerTaskExecutor())  // 使用虚拟线程执行器
                .connectTimeout(Duration.ofSeconds(5))
                .build();
    }
}