1. 개요

이 튜토리얼에서는 Open Feign을 사용하여 파일을 업로드하는 방법을 보여줍니다. Feign 은 마이크로 서비스 개발자가 REST API를 통해 선언적 방식으로 다른 마이크로 서비스와 통신 할 수있는 강력한 도구입니다.

2. 전제 조건

의합시다 편안한 웹 서비스가 노출되어 있다고 가정 세부 사항은 파일 업로드 및 아래 :

POST http://localhost:8081/upload-file

따라서 Feign 클라이언트 를 통한 파일 업로드를 설명하기 위해 아래와 같이 노출 된 웹 서비스 API를 호출합니다.

@PostMapping(value = "/upload-file")
public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
    // File upload logic
}

3. 종속성

하려면 지원하는 응용 프로그램 / x-www-form-urlencoded로다중 / 폼 데이터 타입 인코딩 , 우리가해야합니다 파일 업로드를 체하다 코어 , 체하다 형태 ,체하다 형태의 스프링 모듈.

따라서 Maven에 다음 종속성을 추가합니다.

<dependency>
    <groupId>io.github.openfeign</groupId>
    <artifactId>feign-core</artifactId>
    <version>10.12</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form</artifactId>
    <version>3.8.0</version>
</dependency>
<dependency>
    <groupId>io.github.openfeign.form</groupId>
    <artifactId>feign-form-spring</artifactId>
    <version>3.8.0</version>
</dependency>

내부적 으로 feign -core 가있는 spring-cloud-starter-openfeign사용할 수도 있습니다 .

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <version>3.0.1</version>
</dependency>

4. 구성

기본 클래스 @EnableFeignClients추가해 보겠습니다 . 자세한 내용 spring cloud open feign tutorial을 방문 하십시오.

@SpringBootApplication
@EnableFeignClients
public class ExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

@EnableFeignClients 어노테이션은 Feign 클라이언트로 선언 된 인터페이스에 대한 컴포넌트 스캔을 허용합니다.

5. Feign Client를 통한 파일 업로드

5.1. 주석이 달린 클라이언트를 통해

주석이 달린 @FeignClient 클래스에 필요한 인코더를 만들어 보겠습니다 .

public class FeignSupportConfig {
    @Bean
    public Encoder multipartFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(new ObjectFactory<HttpMessageConverters>() {
            @Override
            public HttpMessageConverters getObject() throws BeansException {
                return new HttpMessageConverters(new RestTemplate().getMessageConverters());
            }
        }));
    }
}

참고 것을 FeignSupportConfig는 주석 할 필요가 없습니다 @Configuration.

이제 인터페이스를 만들고 @FeignClient로 주석을 달아 보겠습니다 . 또한 해당 값과 함께 이름구성 속성추가 합니다.

@FeignClient(name = "file", url = "http://localhost:8081", configuration = FeignSupportConfig.class)
public interface UploadClient {
    @PostMapping(value = "/upload-file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    String fileUpload(@RequestPart(value = "file") MultipartFile file);
}

UploadClient의 API에 대한 포인트에서 언급 한 전제 조건 .

Hystrix로 작업하는 동안 대체 속성으로 추가 하기 위해 fallback 속성을 사용할 것 입니다. 이는 업로드 API가 실패 할 때 수행됩니다 .

이제 @FeignClient는 다음과 같습니다.

@FeignClient(name = "file", url = "http://localhost:8081", fallback = UploadFallback.class, configuration = FeignSupportConfig.class)

마지막으로 서비스 계층에서 직접 UploadClient 를 호출 할 수 있습니다 .

public String uploadFile(MultipartFile file) {
    return client.fileUpload(file);
}

5.2. Feign.builder를 통해

어떤 경우에는 Feign Clients를 사용자 정의해야하는데, 위에서 설명한 주석 방식으로는 불가능합니다. 이 경우 Feign.builder () API를 사용하여 클라이언트를 만듭니다 .

파일 업로드를 위해 REST API를 대상으로하는 파일 업로드 메서드를 포함하는 프록시 인터페이스를 빌드 해 보겠습니다.

public interface UploadResource {
    @RequestLine("POST /upload-file")
    @Headers("Content-Type: multipart/form-data")
    Response uploadFile(@Param("file") MultipartFile file);
}

@RequestLine 주석은 HTTP 메서드와 API의 상대 리소스 경로를 정의하고 @Headers 는 Content-Type과 같은 헤더를 지정합니다.

이제 프록시 인터페이스에서 지정된 메서드를 호출 해 보겠습니다. 서비스 클래스에서이 작업을 수행합니다.

public boolean uploadFileWithManualClient(MultipartFile file) {
    UploadResource fileUploadResource = Feign.builder().encoder(new SpringFormEncoder())
      .target(UploadResource.class, HTTP_FILE_UPLOAD_URL);
    Response response = fileUploadResource.uploadFile(file);
    return response.status() == 200;
}

여기서는 Feign.builder () 유틸리티를 사용하여 UploadResource 프록시 인터페이스 의 인스턴스를 빌드했습니다 . 또한 SpringFormEncoder 및 RESTful 웹 서비스 기반 URL을 사용했습니다.

6. 검증

주석이 달린 클라이언트로 파일 업로드를 확인하는 테스트를 만들어 보겠습니다.

@Test
public void whenAnnotatedFeignClient_thenFileUploadSuccess() {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    File file = new File(classloader.getResource(FILE_NAME).getFile());
    Assert.assertTrue(file.exists());
    FileInputStream input = new FileInputStream(file);
    MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
       IOUtils.toByteArray(input));
    String uploadFile = uploadService.uploadFile(multipartFile);
    Assert.assertNotNull(uploadFile);
}

이제 Feign.Builder () 를 사용하여 파일 업로드를 확인하는 또 다른 테스트를 만들어 보겠습니다 .

@Test
public void whenFeignBuilder_thenFileUploadSuccess() throws IOException {
    // same as above
    Assert.assertTrue(uploadService.uploadFileWithManualClient(multipartFile));
}

7. 결론

이 기사에서는 OpenFeign을 사용하여 멀티 파트 파일 업로드를 구현하는 방법과이를 간단한 애플리케이션에 포함하는 다양한 방법을 보여주었습니다.

또한 동일한 .NET 을 수행하기 위해 Feign 클라이언트를 구성하거나 Feign.Builder ()사용하는 방법도 살펴 보았습니다 .

평소처럼이 자습서에서 사용 된 모든 코드 샘플 은 GitHub에서 사용할 수 있습니다.