Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
..
Failed to load latest commit information.
ahao-spring-cloud-eureka-consumer
ahao-spring-cloud-eureka-provider
ahao-spring-cloud-eureka-server
README.md
pom.xml

README.md

简介

一个Demo, 提供了开箱即用的服务注册中心, 以及三种不同的客户端连接方式.

配置文件

客户端配置文件: application-client.yml 单注册中心配置文件: application-server.yml 多注册中心配置文件: application-server-ha-1.ymlapplication-server-ha-2.yml

三种不同的客户端连接方式

Feign 使用 form data 方式上传文件

要使用Feign提供的一个开源组件feign-form. 在服务消费方配置SpringFormEncoder即可.

@Configuration
@EnableFeignClients(basePackages = "moe.ahao")
@ConditionalOnProperty(name = "eureka.client.enabled", havingValue = "true")
public class FeignConfig {
    @Autowired
    private ObjectFactory<HttpMessageConverters> messageConverters;

    @Bean
    public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
    }
}

@FeignClient(value = serverName)
public interface SimpleFeignClient {
    @PostMapping(value = "/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    AjaxDTO formData(@RequestParam String param, @RequestParam String json, @RequestPart("file") MultipartFile file);
}

@RestController
public class FeignController {
    @Autowired
    private SimpleFeignClient feignClient;

    @PostMapping(value = "/form-data3", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxDTO formData(@RequestParam String param, @RequestParam String json, @RequestPart("file") MultipartFile file) {
        return feignClient.formData(param, json, file);
    }
}

有几个注意点

  1. 使用form data不能@RequestBody@RequestPart一起用, 如果要上传文件, 只能老老实实的把所有参数写在Controller上, 或者使用本解决方案.
  2. feign-form的版本号一定要选对, 具体参考官方文档.
  3. @RequestPart(value = "file", required = false)不生效#126, 如果想要实现可选的文件上传, 需要重载方法
    @FeignClient(value = serverName)
    public interface SimpleFeignClient {
        @PostMapping(value = "/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) // 注意, 这里 body 的 required = false 并不生效
        AjaxDTO formData(@RequestParam String param, @RequestParam String json, @RequestPart(value = "file", required = false) MultipartFile file);
     
        @PostMapping(value = "/form-data", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        AjaxDTO formData(@RequestParam String param, @RequestParam String json);
    }

单元测试

  1. 启动Eureka服务端.
  2. 启动服务提供者.
  3. 执行单元测试
You can’t perform that action at this time.