1. 程式人生 > >Spring Cloud Feign(第四篇)之Fallback

Spring Cloud Feign(第四篇)之Fallback

timg.jpg

Spring Cloud Feign 之Fallback

環境資訊: java 1.8、Spring boot 1.5.10.RELEASE、spring cloud-Edgware.SR3、maven 3.3+

在網路請求時,可能會出現異常請求,如果還想再異常情況下使系統可用,那麼就需要容錯處理,比如:網路請求超時時給使用者提示“稍後重試”或使用本地快照資料等等。

Spring Cloud Feign就是通過Fallback實現的,有兩種方式:

1、@FeignClient.fallback = UserFeignFallback.class指定一個實現Feign介面的實現類。

2、@FeignClient.fallbackFactory = UserFeignFactory.class指定一個實現FallbackFactory<T>工廠介面類

因為Fallback是通過Hystrix實現的, 所以需要開啟Hystrix,spring boot application.properties檔案配置feign.hystrix.enabled=true,這樣就開啟了Fallback

Fallback-實現Feign介面

UserFeignFallback回撥實現,由spring建立使用@Component(其他的註冊也可以)註解

HystrixTargeter.targetWithFallback

方法實現了@FeignClient.fallback處理邏輯,通過原始碼可以知道UserFeignFallback回撥類是從Spring容器中獲取的,所以UserFeignFallback由spring建立。

UserFeign配置:

package com.example.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import
org.springframework.web.bind.annotation.PostMapping; import java.util.List; @FeignClient(name = "user",url = "${user.url}",fallback = UserFeignFallback.class /*fallbackFactory = UserFeignFactory.class*/) public interface UserFeign { @PostMapping void save(User user); @GetMapping("/{id}") User getUserByID(@PathVariable("id") String id); @GetMapping List<User> findAll(); }

UserFeignFallback類:

package com.example.feign;

import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserFeignFallback implements UserFeign {

    @Override
    public void save(User user) {

    }

    @Override
    public User getUserByID(String id) {
        User user = new User();
        user.setId("100");
        user.setName("fallback 回撥使用者");
        return user;
    }

    @Override
    public List<User> findAll() {
        return null;
    }
}

為了模擬回撥失敗服務提供方,丟擲500錯誤。

 @GetMapping("/{id}")
    public User getUserByID(@PathVariable("id") String id) {

//        return userMap.get(id);
        throw new RuntimeException("服務端測試異常!");
    }

執行單元測試UserFeignTest.getUserByID控制檯輸出結果:

2018-08-18 11:47:59.800  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] ---> GET http://localhost:8080/user/1 HTTP/1.1
2018-08-18 11:47:59.800  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] ---> END HTTP (0-byte body)
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] <--- HTTP/1.1 500 (27ms)
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] connection: close
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] content-type: application/json;charset=UTF-8
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] date: Sat, 18 Aug 2018 03:47:59 GMT
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] transfer-encoding: chunked
2018-08-18 11:47:59.828  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] 
2018-08-18 11:47:59.829  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] {"timestamp":1534564079825,"status":500,"error":"Internal Server Error","exception":"java.lang.RuntimeException","message":"服務端測試異常!","path":"/user/1"}
2018-08-18 11:47:59.829  INFO 8660 --- [ hystrix-user-1] com.example.feign.UserFeign              : [UserFeign#getUserByID] <--- END HTTP (167-byte body)
User{id='100', name='fallback 回撥使用者'}

服務提供方丟擲的500錯誤程式碼,但是客戶端程式還可以正常執行輸出了UserFeignFallback.getUserByID方法返回的結果。

FallbackFactory工廠

上面的實現方式簡單,但是獲取不到HTTP請求錯誤狀態碼和資訊 ,這時就可以使用工廠模式來實現Fallback

同樣工廠實現類也要交由spring管理,同時結合UserFeignFallback使用,這裡需要注意的create方法返回值型別一定要實現Feign介面,否則會報錯。

UserFeignFactory只做了列印異常處理:

package com.example.feign;

import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

@Component
public class UserFeignFactory implements FallbackFactory<UserFeign> {

    private final UserFeignFallback userFeignFallback;

    public UserFeignFactory(UserFeignFallback userFeignFallback) {
        this.userFeignFallback = userFeignFallback;
    }

    @Override
    public UserFeign create(Throwable cause) {
        //列印下異常
        cause.printStackTrace();
        return userFeignFallback;
    }
}

UserFeign:

package com.example.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@FeignClient(name = "user", url = "${user.url}",
/*fallback = UserFeignFallback.class*/
        fallbackFactory = UserFeignFactory.class)
public interface UserFeign {

    @PostMapping
    void save(User user);

    @GetMapping("/{id}")
    User getUserByID(@PathVariable("id") String id);

    @GetMapping
    List<User> findAll();
}

執行單元測試UserFeignTest.getUserByID可以看到控制檯列印的異常feign.FeignException更多資訊省略。

ErrorDecoder介面處理請求錯誤資訊,預設實現ErrorDecoder.Default丟擲FeignException異常

FeignException.status 方法返回HTTP狀態碼,FallbackFactory.create預設情況下可以強制轉換成FeignException異常這樣就可以獲取到HTTP狀態碼了。

自定義ErrorDecoder

第一種:application.properties

全域性配置,通過application.properties配置檔案

feign.client.default-config=my-config
feign.client.config.my-config.error-decoder=com.example.feign.MyErrorDecoder

錯誤解碼實現類MyErrorDecoder

package com.example.feign;

import feign.Response;
import feign.codec.ErrorDecoder;

public class MyErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        return new MyFeignException(methodKey,response);
    }
}

自定義異常MyFeignException

package com.example.feign;

import feign.Response;

public class MyFeignException extends RuntimeException {
    private final String methodKey;
    private Response response;


    MyFeignException(String methodKey, Response response) {
        this.methodKey = methodKey;
        this.response = response;
    }


    public Response getResponse() {
        return response;
    }

    public String getMethodKey() {
        return methodKey;
    }
}

第二種:@EnableFeignClients

全域性配置,@EnableFeignClients.defaultConfiguration註解

package com.example;

import com.example.feign.FeignClientsConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

/**
 * 啟動類
 *
 * @author: sunshaoping
 * @date: Create by in 上午10:47 2018/8/7
 */
@EnableFeignClients(
        defaultConfiguration = FeignClientsConfig.class
)
@SpringBootApplication
public class FeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }


}

第三種:@FeignClient

作用範圍是Feign介面,優先順序要高於上面兩種,@FeignClient.configuration 註解

package com.example.feign;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@FeignClient(name = "user", url = "${user.url}",
/*fallback = UserFeignFallback.class*/
        decode404 = true,
        fallbackFactory = UserFeignFactory.class,
        configuration = FeignClientsConfig.class
)
public interface UserFeign {

    @PostMapping
    void save(User user);

    @GetMapping("/{id}")
    User getUserByID(@PathVariable("id") String id);

    @GetMapping
    List<User> findAll();
}

總結

本章節講了如下內容

Spring Cloud Feign HTTP請求異常Fallback容錯機制,它是基於Hystrix實現的,所以要通過配置引數feign.hystrix.enabled=true開啟該功能,及其兩種實現方式。

Fallback工廠方式引出了ErrorDecoder錯誤解碼自定義處理,有三種方式,可根據實際請求選擇,舉一反三其他自定義配置也可以通過這種方式實現如:Decoder、Encoder、Logger(第二、三章有介紹)。

如果開啟的Hystrix就不要用feign的超時配置了,單位是毫秒

feign.client.config.defalut.connect-timeout=10000

defalut是預設配置名稱,可以使用feign.client.default-config替換自定義名稱

feign.client.default-config=my-config
feign.client.config.my-config.connect-timeout=10000

請使用如下屬性配置超時時間,單位毫秒

hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=20000

樣例地址 spring-cloud-feign 分支 Spring-Cloud-Feign-之fallback

寫在最後

Spring Cloud Feign 系列持續更新中。。。。。歡迎關注

如發現哪些知識點有誤或是沒有看懂,請在評論區提出,博主及時改正。

歡迎轉載請註明出處。