1. 程式人生 > >springcloud系列—Feign—第4章-3: Feign 的配置詳解

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