1. 使用Spring的http客户端拦截器
参考链接:www.crud.cool/archives/re…
2. 代理+单例实现
由于一开始想的是使用的时候包一层代理对象,所以写了这个,后来才发现可以使用方法1,比方法2要清晰的多。 但是方法2也是一个不错的参考。
2.1 代理Handler
@Slf4j
public class RestLogPrintHandler implements InvocationHandler {
private Object object;
public RestLogPrintHandler(Object object){
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log.info("废钢定级 RestTemplate【 请求 】 -- 方法【 {} 】 -- 请求参数【 {} 】", method.getName(), args);
Object invoke = method.invoke(object, args);
log.info("废钢定级 RestTemplate【 响应 】 -- 方法【 {} 】 -- 响应结果【 {} 】", method.getName(), invoke);
return null;
}
}
2.2 代理Proxy
@Component
public class RestTemplateProxy {
@Resource
private RestTemplate restTemplate;
private static RestOperations restOperations;
public RestOperations getInstance() {
if (restOperations == null) {
synchronized (RestTemplateProxy.class) {
if (restOperations == null) {
System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
InvocationHandler handler = new RestLogPrintHandler(restTemplate);
restOperations = (RestOperations) Proxy.newProxyInstance(restTemplate.getClass().getClassLoader(), restTemplate.getClass().getInterfaces(), handler);
}
}
}
return restOperations;
}
}
3. 使用
restTemplateProxy.getInstance().postForEntity("http://localhost:8222/snap-result/adopt", snapImageDto, String.class);
4. 效果
5. 总结
还是方法1清晰一些,方法2就当成一个练手吧,后期如果需要代理Spring中的实例,可以借鉴一下。