我的团队正在使用 RestTemplate 进行外部 API 调用。我们需要将 RestTemplate 配置为仅在某些类中使用代理。在所有其他类中,我们希望避免使用代理。我的第一个想法是继续使用不需要代理的@Autowire RestTemplate,并在所有需要代理的类中执行以下操作。我对这个解决方案不满意,因为@Autowire RestTemplate 看起来真的很干净,但必须在每个需要它的类中键入以下代理配置的 RestTemplate。有没有更清洁的替代品?
需要代理
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http.proxy.fmr.com", 8000)));
this.pricingRestTemplate = new RestTemplate(requestFactory);
***解决方案***
为 rest 模板创建了 2 个 bean 并将一个声明为主要的(需要避免错误)
配置类中的新 bean
@Bean
@Primary
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean(name = "proxyRestTemplate")
public RestTemplate proxyRestTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("http.proxy.com", 8000));
requestFactory.setProxy(proxy);
return new RestTemplate(requestFactory);
}
然后我在需要使用代理的地方自动装配并使用了@Qualifier 注释
// no proxy
@Autowired
RestTemplate oauth2RestTemplate;
// yes proxy
@Autowired
@Qualifier("proxyRestTemplate")
RestTemplate proxyRestTemplate;