springcloud系列—Feign—第4章-3: Feign 的配置详解

资料参考:《Spring Cloud 微服务实战》

目录

Ribbon配置

Hystrix配置

其他配置

Feign的文件上传实现

服务提供方(接收文件)

服务消费方(发送文件)


到目前为止,小伙伴们对Feign的使用已经掌握的差不多了,我们在前文也提到Feign是对Ribbon和Hystrix的整合,那么在Feign中,我们要如何配置Ribbon和Hystrix呢?带着这两个问题,我们来看看本文的内容。

Ribbon配置

ribbon的配置其实非常简单,直接在application.properties中配置即可,如下:

# 设置连接超时时间
ribbon.ConnectTimeout=600
# 设置读取超时时间
ribbon.ReadTimeout=6000
# 对所有操作请求都进行重试
ribbon.OkToRetryOnAllOperations=true
# 切换实例的重试次数
ribbon.MaxAutoRetriesNextServer=2
# 对当前实例的重试次数
ribbon.MaxAutoRetries=1

这个参数的测试方式很简单,我们可以在服务提供者的hello方法中睡眠5s,然后调节这个参数就能看到效果。下面的参数是我们配置的超时重试参数,超时之后,首先会继续尝试访问当前实例1次,如果还是失败,则会切换实例访问,切换实例一共可以切换两次,两次之后如果还是没有拿到访问结果,则会报Read timed out executing GET http://hello-service/hello。 
但是这种配置是一种全局配置,就是是对所有的请求生效的,如果我想针对不同的服务配置不同的连接超时和读取超时,那么我们可以在属性的前面加上服务的名字,如下:

# 设置针对hello-service服务的连接超时时间
hello-service.ribbon.ConnectTimeout=600
# 设置针对hello-service服务的读取超时时间
hello-service.ribbon.ReadTimeout=6000
# 设置针对hello-service服务所有操作请求都进行重试
hello-service.ribbon.OkToRetryOnAllOperations=true
# 设置针对hello-service服务切换实例的重试次数
hello-service.ribbon.MaxAutoRetriesNextServer=2
# 设置针对hello-service服务的当前实例的重试次数
hello-service.ribbon.MaxAutoRetries=1

Hystrix配置

Feign中Hystrix的配置和Ribbon有点像,基础配置如下:

# 设置熔断超时时间
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=10000
# 关闭Hystrix功能(不要和上面的配置一起使用)
feign.hystrix.enabled=false
# 关闭熔断功能
hystrix.command.default.execution.timeout.enabled=false

这种配置也是全局配置,如果我们想针对某一个接口配置,比如/hello接口,那么可以按照下面这种写法,如下:

# 设置熔断超时时间
hystrix.command.hello.execution.isolation.thread.timeoutInMilliseconds=10000
# 关闭熔断功能
hystrix.command.hello.execution.timeout.enabled=false

但是我们的接口名可能会重复,这个时候同名的接口会共用这一条Hystrix配置。

OK,我们之前还有一篇文章专门讲Hystrix服务降级的问题,那么在Feign中如何配置Hystrix的服务降级呢?很简单,新建一个类,实现HelloService接口,如下:

@Component
public class HelloServiceFallback implements HelloService {
    @Override
    public String hello() {
        return "hello error";
    }

    @Override
    public String hello(String name) {
        return "error " + name;
    }

    @Override
    public Book hello(String name, String author, Integer price) {
        Book book = new Book();
        book.setName("error");
        return book;
    }

    @Override
    public String hello(Book book) {
        return "error book";
    }
}

这里方法实现的逻辑都是相应的服务降级逻辑。然后在@FeignClient注解中指定服务降级处理类即可,如下:

@FeignClient(value = "hello-service",fallback = HelloServiceFallback.class)
public interface HelloService {
    @RequestMapping("/hello")
    String hello();

    @RequestMapping(value = "/hello1", method = RequestMethod.GET)
    String hello(@RequestParam("name") String name);

    @RequestMapping(value = "/hello2", method = RequestMethod.GET)
    Book hello(@RequestHeader("name") String name, @RequestHeader("author") String author, @RequestHeader("price") Integer price);

    @RequestMapping(value = "/hello3", method = RequestMethod.POST)
    String hello(@RequestBody Book book);
}

此时我们只启动eureka-server和feign-consumer,然后访问相应的接口,可以看到如下结果(注意这里需要在application.properties中配置feign.hystrix.enabled=true,新版本(Dalston.SR3)的Spring Cloud Feign默认是关闭了Hystrix功能的):

其他配置

Spring Cloud Feign支持对请求和响应进行GZIP压缩,以提高通信效率,配置方式如下:

# 配置请求GZIP压缩
feign.compression.request.enabled=true
# 配置响应GZIP压缩
feign.compression.response.enabled=true
# 配置压缩支持的MIME TYPE
feign.compression.request.mime-types=text/xml,application/xml,application/json
# 配置压缩数据大小的下限
feign.compression.request.min-request-size=2048

Feign为每一个FeignClient都提供了一个feign.Logger实例,我们可以在配置中开启日志,开启方式很简单,分两步:

第一步:application.properties中配置日志输出 
application.properties中配置如下内容,表示设置日志输出级别:

# 开启日志 格式为logging.level.+Feign客户端路径
logging.level.org.sang.HelloService=debug

第二步:入口类中配置日志Bean

入口类中配置日志Bean,如下:

@Bean
Logger.Level feignLoggerLevel() {
    return Logger.Level.FULL;
}

OK,如此之后,控制台就会输出请求的详细日志。

Feign的文件上传实现

在Spring Cloud封装的Feign中并不直接支持传文件,但可以通过引入Feign的扩展包来实现,本来就来具体说说如何实现。

服务提供方(接收文件)

服务提供方的实现比较简单,就按Spring MVC的正常实现方式即可,比如:

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    @RestController
    public class UploadController {

        @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
            return file.getName();
        }

    }

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

服务消费方(发送文件)

在服务消费方由于会使用Feign客户端,所以在这里需要在引入feign对表单提交的依赖,具体如下:

<dependency>
   <groupId>io.github.openfeign.form</groupId>
   <artifactId>feign-form</artifactId>
   <version>3.0.3</version>
</dependency>
<dependency>
   <groupId>io.github.openfeign.form</groupId>
   <artifactId>feign-form-spring</artifactId>
   <version>3.0.3</version>
</dependency>
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>

定义文件上传方的应用主类和FeignClient,假设服务提供方的服务名为eureka-feign-upload-server

feign-upload-server

@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}

@FeignClient(value = "upload-server", configuration = UploadService.MultipartSupportConfig.class)
public interface UploadService {
 
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    String handleFileUpload(@RequestPart(value = "file") MultipartFile file);
 
    @Configuration
    class MultipartSupportConfig {
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder();
        }
    }
 
}

在启动了服务提供方之后,尝试在服务消费方编写测试用例来通过上面定义的Feign客户端来传文件,比如:

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class UploadTester {

    @Autowired
    private UploadService uploadService;

    @Test
    @SneakyThrows
    public void testHandleFileUpload() {

        File file = new File("upload.txt");
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        MultipartFile multi = new CommonsMultipartFile(fileItem);

        log.info(uploadService.handleFileUpload(multi));
    }

}

Github:https://github.com/servef-toto/SpringCloud-Demo/tree/master/SpringCloudLearing

猜你喜欢

转载自blog.csdn.net/weixin_40663800/article/details/84789159