RestTemplateConfig.java
2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.bs.reception.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.time.Duration;
@Slf4j
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// 使用 RestTemplateBuilder 构建具有定制配置的 RestTemplate
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(30_000);
factory.setReadTimeout(60_000);
return builder
.additionalInterceptors(new RestTemplateLoggingInterceptor())
.requestFactory(() -> new BufferingClientHttpRequestFactory(factory))
.build();
}
/**
* 日志拦截器(可选)
*/
static class RestTemplateLoggingInterceptor implements org.springframework.http.client.ClientHttpRequestInterceptor {
@Override
public org.springframework.http.client.ClientHttpResponse intercept(
org.springframework.http.HttpRequest request,
byte[] body,
org.springframework.http.client.ClientHttpRequestExecution execution) throws java.io.IOException {
// 记录请求日志
log.info("请求URL: " + request.getURI());
log.info("请求方法: " + request.getMethod());
log.info("请求头: " + request.getHeaders());
org.springframework.http.client.ClientHttpResponse response = execution.execute(request, body);
// 记录响应日志
log.info("响应状态: " + response.getStatusCode());
log.info("响应头: " + response.getHeaders());
return response;
}
}
}