項(xiàng)目實(shí)戰(zhàn)中捎拯,不可避免的會(huì)調(diào)用第三方接口滴铅,調(diào)用同一個(gè)廠商的第三方接口時(shí)會(huì)有著相同的邏輯,例如延簽邏輯筋量、設(shè)置header邏輯湖苞,我們可以定制化實(shí)現(xiàn)RestTemplate的bean拯欧。將公共邏輯進(jìn)行解耦。
1. 自定義RestTemplate
為每一個(gè)廠商均實(shí)現(xiàn)單獨(dú)的RestTemplate的bean财骨,完成定制化操作镐作。
@Configuration
public class MyRestTemplateConfig {
@Bean(name = "myRestTemplate")
public RestTemplate wpsRestTemplate(WPSConfigProperties wpsConfigProperties) {
//定制化可重復(fù)讀的響應(yīng)對(duì)象的裝飾器類。
//可替換為OkHttp隆箩。
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(1000);
factory.setReadTimeout(3000);
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(factory));
//處理消息轉(zhuǎn)換器
for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
if (converter instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
}
}
//設(shè)置攔截器该贾。處理公共邏輯
restTemplate.setInterceptors(Arrays.asList(
myRestAuthInterceptor(myConfigProperties),
restTemplateMetricsInterceptor()));
return restTemplate;
}
//驗(yàn)簽的攔截器
@Bean
public MyRestAuthInterceptor myRestAuthInterceptor(MyConfigProperties myConfigProperties) {
return new MyRestAuthInterceptor(myConfigProperties);
}
//監(jiān)控的攔截器
@Bean
public RestTemplateMetricsInterceptor restTemplateMetricsInterceptor() {
return new RestTemplateMetricsInterceptor();
}
}
2. 實(shí)現(xiàn)定制化的攔截器
在定制化的攔截器中完成某一個(gè)廠商的所有第三方接口的定制化操作。包含日志操作或者延簽操作等等捌臊。
@Slf4j
public class MyRestAuthInterceptor implements ClientHttpRequestInterceptor {
private MyConfigProperties myConfigProperties;
public MyRestAuthInterceptor(MyConfigProperties myConfigProperties) {
this.myConfigProperties = myConfigProperties;
}
/**
* techhub-auth 新增該body杨蛋,存放wps下發(fā)的appId
*/
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
//延簽邏輯
long startTime = System.currentTimeMillis();
ClientHttpResponse response = execution.execute(request, body);
try {
//讀取流為String
String responseBody = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset());
//打印日志
loggerInfo(request, body, startTime, responseBody);
} catch (Exception e) {
//不打印異常
log.error("", e);
}
return response;
}
/**
* 收集日志信息
*
* @param request 請(qǐng)求對(duì)象
* @param body 請(qǐng)求體
* @param startTime 請(qǐng)求發(fā)送事件
* @param responseBody 響應(yīng)對(duì)象
*/
private void loggerInfo(HttpRequest request, byte[] body, long startTime, String responseBody) {
SealLogger.log("my request is uri:{},body:{}娃属,executeTime:{}ms\n" +
"my response :{}",
request.getURI(), new String(body), System.currentTimeMillis() - startTime, responseBody);
}
}