繁体   English   中英

Spring Boot Rest 模板代理只有几个类

[英]Spring Boot Rest Template Proxy In Only Few Classes

我的团队正在使用 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;

在类的构造函数中注入RestTemplate (或者更好的RestOperations )(无论如何这是最佳实践),对于需要代理配置的类,使用@Bean配置方法来实例化 bean 并传递特定的代理模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM