1. 问题描述
- 使用SpringCloud 集成 Feign访问远程服务,并在使用hystrix 在客户端做了服务降级
- 服务降级配置类 DeptClientServiceFallBackFactory.java
package com.zy.service;
import com.zy.pojo.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
// DeptService 服务降级配置类
public class DeptServiceFallBackFactory implements FallbackFactory {
@Override
public DeptService create(Throwable throwable) {
return new DeptService() {
@Override
public boolean addDept(Dept dept) {
return false;
}
@Override
public boolean deleteDept(Long id) {
return false;
}
@Override
public boolean updateDept(Dept dept) {
return false;
}
@Override
public List<Dept> queryDept(Dept dept) {
return null;
}
@Override
public Dept getDept(Long id) {
return new Dept()
.setId(id)
.setName("id=>" + id + "没有对应的信息,客户端提供了降级的信息,这个服务现在已经被关闭")
.setDbSource("没有数据 ... ");
}
};
}
}
- 在 service/DeptService 中指定服务降级配置类 DeptServiceFallBackFactory
package com.zy.service;
import com.zy.pojo.Dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
// @FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
// fallbackFactory指定降级配置类,如果这个接口对应的远程服务关闭了,返回 DeptServiceFallBackFactory 中配置的信息
@Service //注册到spring容器中
@FeignClient(value = "PROVIDER", fallbackFactory = DeptServiceFallBackFactory.class)
public interface DeptService {
@PostMapping(path = "/dept/add")
boolean addDept(@RequestBody Dept dept);
@GetMapping(path = "/dept/delete/{id}")
boolean deleteDept(@PathVariable("id") Long id);
@PostMapping(path = "/dept/update")
boolean updateDept(@RequestBody Dept dept);
// 枚举列表
@PostMapping(path = "/dept/query")
List<Dept> queryDept(@RequestBody Dept dept);
// 查询一个满足条件的对象
@GetMapping(path = "/dept/get/{id}")
Dept getDept(@PathVariable("id") Long id);
}
- 在consumer-feign 的配置文件application.yaml 中 开启服务降级配置
server:
port: 9001
# Eureka配置
eureka:
client:
register-with-eureka: false # 不向 Eureka 注册自己
service-url: # 注册中心地址
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
# 开启服务降级feign.hystrix
feign:
hystrix:
enabled: true
- 报错
IllegalStateException: No fallbackFactory instance of type class com.zy.service.DeptServiceFallBackFactory
2. 原因分析
找不我们的服务降级配置类,要么路径错误,要么没注入到Spring 容器,检查后发现是后者
3. 解决方案
在 服务降级配置类 上添加注解 @Component,将服务降级配置类注入到Spring 容器
// DeptService 服务降级配置类
@Component // 注入到Spring (注意:这里的注解不要忘记!!!)
public class DeptServiceFallBackFactory implements FallbackFactory {
...
}