Feign Hystrix整合&服务熔断服务降级彻底解耦
前面的代码,用@HystrixCommand fallbackMethod是很不好的,因为和业务代码耦合度太高,不利于维护,所以需要解耦,这我们讲下Feign Hystrix整合。
第一,microservice-student-provider-hystrix-1004项目修改
我们不用原先那套。按照正常的逻辑来写;
StudentService加新的接口方法:
/** * 获取信息 * @return */ public Map<String,Object> getInfo();
StudentServiceImpl写具体实现:
@Override public Map<String, Object> getInfo() { Map<String,Object> map=new HashMap<String,Object>(); map.put("code", 200); map.put("info", "业务数据xxxxx"); return map; }
StudentProviderController正常调用service方法:
/** * 获取信息 * @return * @throws InterruptedException */ @ResponseBody @GetMapping(value="/getInfo") public Map<String,Object> getInfo() throws InterruptedException{ Thread.sleep(900); return studentService.getInfo(); }
第二步:microservice-common项目新建FallbackFactory类,解耦服务熔断服务降级
StudentClientService接口,新增getInfo方法;
/** * 获取信息 * @return */ @GetMapping(value="/student/getInfo") public Map<String,Object> getInfo();
新建 StudentClientFallbackFactory 类,实现FallbackFactory<StudentClientService>接口;
package com.java1234.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Component; import com.java1234.entity.Student; import feign.hystrix.FallbackFactory; @Component public class StudentClientFallbackFactory implements FallbackFactory<StudentClientService>{ @Override public StudentClientService create(Throwable cause) { // TODO Auto-generated method stub return new StudentClientService() { @Override public boolean save(Student student) { // TODO Auto-generated method stub return false; } @Override public List<Student> list() { // TODO Auto-generated method stub return null; } @Override public Map<String, Object> getInfo() { Map<String,Object> map=new HashMap<String,Object>(); map.put("code", 500); map.put("info", "系统出错,稍后重试"); return map; } @Override public Student get(Integer id) { // TODO Auto-generated method stub return null; } @Override public boolean delete(Integer id) { // TODO Auto-generated method stub return false; } }; } }
StudentClientService接口的@FeignClient注解加下 fallbackFactory属性
@FeignClient(value="MICROSERVICE-STUDENT",fallbackFactory=StudentClientFallbackFactory.class)
这类我们实现了 降级处理方法实现;
第三步:microservice-student-consumer-feign-80修改 支持Hystrix
StudentConsumerFeignController新增方法调用
/** * 根据id删除学生信息 * @return */ @GetMapping(value="/getInfo") @ResponseBody public Map<String,Object> getInfo(){ return studentClientService.getInfo(); }
application.yml加上hystrix支持
feign:
hystrix:
enabled: true
测试开启三个eureka,以及带hystrix的provider,和带feign,hystrix的consummer。
测试的话,也是没问题的。0.9秒的话,返回正常信息;超过1秒的话,就返回错误提示;