Spring Cloud Feign 之Fallback

timg.jpg

迁移到CSDN

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<T>工厂

上面的实现方式简单,但是获取不到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 系列持续更新中。。。。。欢迎关注

如发现哪些知识点有误或是没有看懂,请在评论区提出,博主及时改正。

欢迎转载请注明出处。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容