一个feign使用不当的问题

摘要: 一个feign使用不当的问题

正文:

一个错误的示例

接口与回退逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
@FeignClient(name = "service-A",fallback=AServiceFallback.class )
public interface AService {
@RequestMapping(value = "/aApi/getA", method = RequestMethod.GET)
List<AInfo> getA();
}
@Slf4j
public class AServiceFallback implements AService{

@Override
public List<AInfo> getA() {
log.error("进入回退方法:异常");
}
}

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 50000
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
eureka:
enabled: true

以上配置在不熟悉feign-hystrix 或者查看 Feign Hystrix Fallbacks 的可能感觉并没有问题,项目启动也是正常

正确使用方式

接口与回退逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@FeignClient(name = "service-A",fallback=AServiceFallback.class )
public interface AService {
@RequestMapping(value = "/aApi/getA", method = RequestMethod.GET)
List<AInfo> getA();
}
@Slf4j
@Component
public class AServiceFallback implements AService{

@Override
public List<AInfo> getA() {
log.error("进入回退方法:异常");
}
}

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 50000
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
eureka:
enabled: true

feign:
hystrix:
enabled: true

可以看到,在配置文件中新增了feign.hystrix.enabled = true 进行激活,如果代码不变启动项目会报:

1
Caused by: java.lang.IllegalStateException: No fallback instance of type class com.yss.xx.feign.fallback.AServiceFallback found for feign client service-A

可以参考Feign Hystrix Support ,也可以在回退逻辑接口的类上面使用Spring 通用模式装配注解@ComponentAServiceFallback进行装配