SpringCloud 调用上传文件的服务

代码:


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.cloud.netflix.feign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;


import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;


@FeignClient(name = "file-service",
    configuration = IFileUploadService.MultipartSupportConfig.class,
    fallback = FileUploadServiceHystrixImpl.class)

public interface IFileUploadService {
  @Configuration
  class MultipartSupportConfig {
    @Bean
    public Encoder feignFormEncoder() {
      return new SpringFormEncoder(new SpringEncoder(new ObjectFactory() {
        @Override
        public HttpMessageConverters getObject() throws BeansException {
          return new HttpMessageConverters(new RestTemplate().getMessageConverters());
        }
      }));
    }
  }

  /**
   * 后端上传
   *
   * @param file
   * @return
   */
  @RequestMapping(value = "/xxx/upload", method = RequestMethod.POST,
      produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
      consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
  Result uploadOne(@RequestPart(value = "file") MultipartFile file);
}

熔断方法

@Component
public class FileUploadServiceHystrixImpl implements IFileUploadService {
  @Override
  public String uploadOne(MultipartFile files) {
    return "upload error";
  }
}

你可能感兴趣的:(spring,cloud)