本章案例基于SpringCloud feign搭建
业务说明:假设银行有3个窗口A,B,C,每个窗口提供不同的业务,现在A窗口的服务人员,人手不够急需从C或者B窗口调人处理业务,C或者B窗口挂起暂停服务的牌子
步骤一:修改SpringCloud -api工程,创建一个新的类实现FallBackFactory接口
package com.gcxzflgl.springCloud.service;
import java.util.List;
import org.springframework.stereotype.Component;
import com.gcxzflgl.springCloud.entity.Dept;
import feign.hystrix.FallbackFactory;
@Component // 不要忘记添加
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
@Override
public DeptClientService create(Throwable throwable)
{
return new DeptClientService() {
@Override
public Dept get(long id)
{
Dept dept = new Dept();
dept.setDeptno(id);
dept.setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭");
dept.setDb_source("no this database in MySQL");
return dept;
}
@Override
public List<Dept> list()
{
return null;
}
@Override
public boolean add(Dept dept)
{
return false;
}
};
}
}
package com.gcxzflgl.springCloud.service;
import java.util.List;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gcxzflgl.springCloud.entity.Dept;
//@FeignClient(value = "MICROSERVICECLOUD-DEPT")
@FeignClient(value = "MICROSERVICECLOUD-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class)
public interface DeptClientService
{
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
public Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
public List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
public boolean add(Dept dept);
}
这两个类说明,如果发生任何异常,进入全局断路器里根据错误返回不同的提示
然后,mvn clean->mvn install 打包成jar,供其他模块调用
步骤二:修改feign工程applcation.yml,添加如下
feign:
hystrix:
enabled: true
步骤三:启动7001,7002,7003三个Eureka,启动provider-dept-8001,再启动feign,正常访问localhost/consumer/dept/get/1能正常返回数据,如果现在关闭8001端口也就是C或者B窗口提示如下:
此时服务已经down掉,但做了降级处理,让客户端在服务端不可用时也会获得提示信息而不会挂起服务器!