springcloud-hystrix断路器

2020-07-09  本文已影响0人  jiahzhon

什么是hystrix

服务熔断(服务提供方上的开发)

  <!-- hystrix -->
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix</artifactId>
  </dependency>
@RestController
public class DeptController
{
 @Autowired
 private DeptService service = null;

 @RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
 //一旦调用服务方法失败并抛出了错误信息后,会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
 @HystrixCommand(fallbackMethod = "processHystrix_Get")
 public Dept get(@PathVariable("id") Long id)
 {

  Dept dept = this.service.get(id);
  
  if (null == dept) {
   throw new RuntimeException("该ID:" + id + "没有没有对应的信息");
  }
  
  return dept;
 }

 public Dept processHystrix_Get(@PathVariable("id") Long id)
 {
  return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,null--@HystrixCommand")
    .setDb_source("no this database in MySQL");
 }
}

服务降级(服务接收方的开发)

@Component // 不要忘记添加,不要忘记添加
public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>
{
 @Override
 public DeptClientService create(Throwable throwable)
 {
  return new DeptClientService() {
   @Override
   public Dept get(long id)
   {
    return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭")
      .setDb_source("no this database in MySQL");
   }

   @Override
   public List<Dept> list()
   {
    return null;
   }

   @Override
   public boolean add(Dept dept)
   {
    return false;
   }
  };
 }
}
@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);
}
feign: 
  hystrix: 
    enabled: true

熔断和降级

hystrix-dashboard

  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
  </dependency>
  <!-- actuator监控信息完善 -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-actuator</artifactId>
  </dependency>
image.png
上一篇 下一篇

猜你喜欢

热点阅读