前言
最近有个想法想整理一个内容比较完整springboot项目初始化Demo。
SpringBoot使用RestTemplate由服务端向外发起网络请求
一、将RestTemplate
配置初始化为一个Bean
修改RestTemplate
默认的客户端,例如将其改成HttpClient
客户端
package com.murg.bootdemo.config;
import com.murg.bootdemo.interceptor.HeaderRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class RestClientConfig {
@Bean
public ClientHttpRequestFactory clientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(180000);//设置连接超时时间
factory.setReadTimeout(180000);//读取超时时间
return factory;
}
/**
* DependsOn注解用于确保所使用的bean已被初始化
* @param clientHttpRequestFactory 设置
* @return org.springframework.web.client.RestTemplate
*/
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HeaderRequestInterceptor());
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory);
restTemplate.setInterceptors(interceptors);
return restTemplate;
// //配置HTTP超时时间
// HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(
// HttpClientBuilder.create()
// .setMaxConnTotal(100)//最大连接池
// .setMaxConnPerRoute(50)//每个池最大连接数
// .build());
// httpRequestFactory.setConnectTimeout(120000);
// httpRequestFactory.setReadTimeout(180000);
// return new RestTemplate(httpRequestFactory);
}
}
二、使用RestTemplate
TestRestController 注入 RestTemplate
新增测试/rest/authenticate 接口 通过RestTemplate方式获取token
@RequestMapping(value = "/rest/authenticate", method = RequestMethod.GET)
public WebResult restAuthenticate(){
String url = "http://127.0.0.1:8081/api/authenticate";
// 由于获取student接口咱们设置了basicauth,所以需要在请求时配置
HttpHeaders headers = new HttpHeaders();
// 需要传递FORMDATA的请求参数
headers.setContentType(MediaType.APPLICATION_JSON);
Map params =new HashMap();
params.put("username", "admin");
params.put("password", "123456");
params.put("clientid", "clientid");
HttpEntity httpEntity = new HttpEntity(params, headers);
ResponseEntity<WebResult> response = null;
try {
// 通过POST方式调用接口,如果需要PUT,DELETE方式调用
// 只需要修改为HttpMethod.PUT,HttpMethod.DELETE即可,其他传递参数已经代码一致
response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, WebResult.class);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return response.getBody();
}
三、自定义HeaderRequestInterceptor拦截器
自定义HeaderRequestInterceptor继承ClientHttpRequestInterceptor的拦截器。处理Header信息,此处增加接口访问时间打印
package com.murg.bootdemo.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import java.io.IOException;
/**
* @version 1.0
* @Description: 给不同的请求地址 添加不同的header
*/
@Slf4j
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
long startTime = System.currentTimeMillis();
ClientHttpResponse response= null;
try {
response = execution.execute(request, body);
} catch (IOException e) {
throw e;
}finally {
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
log.info("Request URL: " + request.getURI() + " 耗时 " + duration + "ms");
}
return response;
}
}
四、postman测试
控制台打印耗时
[Request URL: http://127.0.0.1:8081/api/authenticate 耗时 10ms]