Как вызвать другой API REST для загрузки файлов с помощью RestTemplate в Springboot - PullRequest
0 голосов
/ 03 апреля 2020

У меня есть служба REST, которая принимает MultiPartFile и сохраняет их в БД. Этот API работает отлично. Я могу загружать документы от чванства и почтальонов. API выглядит следующим образом:

   @PostMapping(value = "upload")
@ResponseStatus(HttpStatus.CREATED)
public UploadResponse uploadAttachment( @RequestParam("documentType") final String documentType,
                                           @RequestParam("attachment") final MultipartFile multipartFile) {

    return uploadService.uploadAttachment(multipartFile, documentType, customerId);
}

Теперь у меня есть еще один микросервис, который также основан на springboot и graphql. Я написал REST API для загрузки файлов, который использует предыдущий API из другого микросервиса. Поскольку GraphQL не поддерживает загрузку и загрузку файлов, я написал ниже Клиентский вызов для загрузки документа.

@Component
@Slf4j
@Data
public class AttachmentClient {
      @Autowired
    @Qualifier("m2mRestTemplate")
    private RestTemplate restClient;


    public UploadtResponse uploadAttachment(MultipartFile multipartFile, String documentType) throws Exception {
        //complete path of the upload URI
        String uploadUri={complete path of upload}

        ObjectMapper mapper = new ObjectMapper();
        File fileToSend = new File(System.getProperty("java.io.tmpdir") + "/" + multipartFile.getOriginalFilename());
        multipartFile.transferTo(fileToSend);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("attachment", new FileSystemResource(fileToSend));
        body.add("documentType", documentType);
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "multipart/form-data");
        HttpEntity httpEntity = new HttpEntity<>(body, headers);
        String jsonInput = restClient.postForEntity(uploadUri", httpEntity, String.class).getBody();
        UploadResponse response = mapper.readValue(jsonInput, new TypeReference<UploadResponse>() {
        });

        return response;
    }
}

Но странно, что приведенный выше код работает некоторое время, когда я запускаю Сервис, но через 10-15 минут он начинает бросать ниже исключения

exception=org.springframework.http.converter.HttpMessageConversionException, originalMessage=Type definition error: [simple type, class java.nio.channels.Channels$1]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.nio.channels.Channels$1 and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["attachment"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["outputStream"]), stackTrace=org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class java.nio.channels.Channels$1]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.nio.channels.Channels$1 and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.util.LinkedMultiValueMap["attachment"]->java.util.LinkedList[0]->org.springframework.core.io.FileSystemResource["outputStream"])

и stackTrace

org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293)
at org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:103)
at org.springframework.web.client.RestTemplate$HttpEntityRequestCallback.doWithRequest(RestTemplate.java:938)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:732)
at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:128)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:669)
at org.springframework.web.client.RestTemplate.postForEntity(RestTemplate.java:444)
at com.netcracker.solutions.cloud.rss.cimapi.restapi.client.AttachmentClient.uploadAttachment(AttachmentClient.java:119)
...