SpringBoot中HTTP高效能客戶端實現

Bruce.Chang.Lee發表於2024-12-05

目錄
  • 1、引入 OKHTTP 依賴
  • 2、配置 OkHttpClient 客戶端例項
  • 3、請求呼叫

1、引入 OKHTTP 依賴

		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
			<version>4.12.0</version>
		</dependency>

2、配置 OkHttpClient 客戶端例項

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class OkHttpConfiguration {

    @Bean
    public okhttp3.OkHttpClient okHttpClient() {
        final okhttp3.Dispatcher dispatcher = new okhttp3.Dispatcher();
        dispatcher.setMaxRequests(Integer.MAX_VALUE);
        dispatcher.setMaxRequestsPerHost(Integer.MAX_VALUE);

        return new okhttp3.OkHttpClient.Builder()
                .connectionPool(new okhttp3.ConnectionPool(200, 5L, TimeUnit.MINUTES))
                .dispatcher(dispatcher)
                .connectTimeout(2, TimeUnit.SECONDS)
                .readTimeout(3, TimeUnit.SECONDS)
                .build();
    }

}

3、請求呼叫

import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@RestController
public class IndexController {

    private final OkHttpClient okHttpClient;

    public IndexController(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
    }

    @GetMapping(path = "index", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> execute(String arg) {
        final Map<String, Object> result = new HashMap<>(3);
        final Request request = new Request.Builder()
                .url("http://x.y.z/ivr/index")
                .post((new FormBody.Builder()).build())
                .build();

        final CompletableFuture<String> future = new CompletableFuture<>();
        this.okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                future.completeExceptionally(e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    future.complete(response.body().string());
                } else {
                    future.completeExceptionally(new IOException("Unexpected code " + response));
                }
            }

        });

        result.put("timestamp", LocalDateTime.now());
        result.put("arg", arg);
        final String futureResult;
        try {
            futureResult = future.get();
            result.put("txt", futureResult);
        } catch (InterruptedException | ExecutionException e) {
            result.put("txt", e.getMessage());
        }


        return result;
    }
}

相關文章