java - 下面提到的使用 org.springframework.web.client.RestTemplate RestTemplate 的潜在问题是什么?

标签 java spring http-headers apache-httpclient-4.x resttemplate

这是我的应用程序的主类

@SpringBootApplication (scanBasePackages = { "com.xyz.*" })
@EnableAsync
@EnableAspectJAutoProxy (proxyTargetClass=true)
@EnableScheduling
public class XyzApplication {

    public static void main(String[] args) {
        SpringApplication.run(XyzApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        builder.requestFactory(new HttpComponentsClientHttpRequestFactory());
        return builder.build();
    }
}

在多个服务和组件中,此 RestTemplate 正在 Autowiring 。

就像在 Controller 中一样,它的使用方式如下

@RestController
@RequestMapping({ "my-api" })
public class CommonController {

    @Autowired
    AppConfig appConfig;

    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("check")
    public String pwa() {
        ResponseEntity<String> response = restTemplate.getForEntity(appConfig.getApiConfig().get("ApiURL"), String.class);
        if (HttpStatus.OK == response.getStatusCode()) {
            return response.getBody().toString();
        } else {
            Logger.error(this.getClass(), "Api is not working");
        }

        return null;

    }
}

在不同的服务中,例如

@Service
public class DetailsQuery {

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Async
    public Future<ConcurrentHashMap<String, Object>> getDetails(JSONObject object) throws InterruptedException, RestClientException {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

        HttpEntity<String> entity = new HttpEntity<String>(object.toString(), headers);

        Map<String, Object> jsonObject = restTemplate.postForObject(new URI(appConfig.getApiConfig().get("searchApi")), entity, Map.class);

        ConcurrentHashMap<String, Object> response = new ConcurrentHashMap<String, Object>();
        response.putAll(jsonObject);

        return new AsyncResult<ConcurrentHashMap<String,Object>>(new ConcurrentHashMap<>(response));

    }

}

问题是这个实现会抛出

There was an unexpected error (type=Internal Server Error, status=500). I/O error on GET request for "http://xx.xxxxxx.xxx/xxxx/xxxx/xxxxxx":

即使curl请求相同的作品,这也会间歇性地产生。

最佳答案

您可以查看的是,您正在自动连接 RestTemplate 单例对象,但是,每次调用该方法时,它都会将相同的消息转换器添加到 RestTemplate 中。

请记住,resttemplate 一旦构造后就是线程安全的,但处理消息转换器在构造后可能不是线程安全的。看看这个线程的例子:

Is RestTemplate thread safe?

您可以尝试执行如下操作,为您的服务创建一个resttemplate实例

@Service
public class DetailsQuery {

  private final RestTemplate restTemplate;

  @Autowired
  public DetailsQuery (RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = restTemplateBuilder.additionalMessageConverters(new MappingJackson2HttpMessageConverter()) build();
  }

  ....
}

或者在创建单例 Resttemplate 对象的 @Config 类中执行相同的操作。

关于java - 下面提到的使用 org.springframework.web.client.RestTemplate RestTemplate 的潜在问题是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42953677/

相关文章:

java - JFrame Java setColor 和 fillRect 保持空白?

java - 如何使用 Spinner.setAdapter 在 Spinner 中显示字符串数组?

java - IdentityHashMap 和 expectedmaxsize

java - 使用 Spring Jpa 为服务插入语句

spring - 如何在 Spring Data JPA CRUDRepository 中添加缓存功能

java - org.hibernate.MappingException - 复合 id

http - 移除 http referer

java - 嵌套 if、else if,不带括号

html - Angular 2 中的访问控制允许 Origin 问题

java - DefaultHttpHeaderMapper 允许自定义,但不执行排除逻辑