添加异常降级工厂类DeptClientServiceFallbackFactory
package org.springcloud.service;import java.util.List;import org.springcloud.pojo.Dept;import org.springframework.stereotype.Component;import feign.hystrix.FallbackFactory;// 降级/*** @author My 接口异常熔断退回 FallbackFactory*/@Componentpublic class DeptClientServiceFallbackFactory implements FallbackFactory {public DeptClientService create(Throwable cause) {return new DeptClientService() {public boolean addDept(Dept dept) {return false;}public Dept queryById(Long deptno) {return new Dept().setDeptno(deptno).setDname("id=>" + deptno + ",没有对应信息。").setDb_source("没有数据");}public List<Dept> queryList() {return null;}};}}
之前是对某一个接口进行,熔断,现在是针对整个接口类进行服务降级处理。
在接口注解使用@FeignClient中,有其他属性,如果fallbackFactory设置返回类
修改DeptClientService接口类
package org.springcloud.service;import java.util.List;import org.springcloud.pojo.Dept;import org.springframework.cloud.openfeign.FeignClient;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;@FeignClient(name = "SPRINGCLOUD-PROVIDER-DEPT", fallbackFactory = DeptClientServiceFallbackFactory.class)public interface DeptClientService {@PostMapping("/dept/add")public boolean addDept(Dept dept);@GetMapping("/dept/queryById/{deptno}")public Dept queryById(@PathVariable("deptno") Long deptno);@GetMapping("/dept/queryList")public List<Dept> queryList();}
在feign服务消费方开启熔断降级
#服务消费者只需要配置启动端口server:port: 8090# eureka配置eureka:client:register-with-eureka: false # 不想eureka中注册自己,消费不需要注册自己service-url:# 服务注册到哪里 打开eureka服务配置以配置中的地址为准# eureka配置好之后,开启eureka功能注解defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7001.com:7002/eureka/,http://eureka7001.com:7003/eureka/# 开启hystrix服务降级feign:hystrix:enabled: true
服务熔断是在服务提供方做的,服务降级是在服务消费者端做的
启动各个服务
正常访问
现在停止服务提供方,再进行访问测试。
不会有报错信息,而是返回设置好的降级内容信息。
服务熔断和服务降级
服务熔断:
服务端
某个服务超时或异常出现,引起熔断,类似保险丝
服务降级:
客户端
从网站整体请假负载考虑,当某个服务熔断或进行关闭,服务将不再被调用,此时可以在客户端,准备一个FallbackFactory,返回一个默认(缺省)值。
好处:服务的负载降低了,缺点是,整体的服务水平下降了,但是好歹能用,可以访问。
