springboot集成hystrix熔断机制

这是一个简单的例子,hystrix的参数配置因为比较多会在之后写出来。可以先参考,跑起来一个小例子。

1、概念:Hystrix 熔断机制

当调用服务出现问题之后整个系统会出现错误的提示信息,而这个时候如果不想出现这样的错误信息,而希望替换一个错误的内容。

springboot集成hystrix熔断机制

一个服务挂了后续的服务跟着不能用了,这就是雪崩效应

对于熔断技术的实现需要考虑以下几种情况:

· 出现错误之后可以 fallback 错误的处理信息;

· 如果要结合 Feign 一起使用的时候还需要在 Feign(客户端)进行熔断的配置(feign以后再写)。

Hystrix 基本配置

org.springframework.cloud

spring-cloud-starter-hystrix

package cn.study.microcloud.rest;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cn.study.microcloud.service.IDeptService;

import cn.study.vo.Dept;

@RestController

public class DeptRest {

@Resource

private IDeptService deptService;

@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)

@HystrixCommand(fallbackMethod="getFallback") // 如果当前调用的get()方法出现了错误,则执行fallback

public Object get(@PathVariable("id") long id) {

Dept vo = this.deptService.get(id) ; // 接收数据库的查询结果

if (vo == null) { // 数据不存在,假设让它抛出个错误

throw new RuntimeException("部门信息不存在!") ;

}

return vo ;

}

public Object getFallback(@PathVariable("id") long id) { // 此时方法的参数 与get()一致

Dept vo = new Dept() ;

vo.setDeptno(999999L);

vo.setDname("【ERROR】Microcloud-Dept-Hystrix"); // 错误的提示

vo.setLoc("DEPT-Provider");

return vo ;

}

}

如果 get()方法抛出错误信息,会默认使用“@HystrixCommand”注解之中配置好的 fallbackMethod 调用类中的指定方法,这里配置的是getFallback()方法

启动类中配置

package cn.study.microcloud;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication

@EnableEurekaClient

@EnableCircuitBreaker

@EnableDiscoveryClient

@EnableHystrixDashboard // hystrix的监控

public class Dept_8001_StartSpringCloudApplication {

public static void main(String[] args) {

SpringApplication.run(Dept_8001_StartSpringCloudApplication.class, args);

}

}

HystrixDashboard服务监控配置

org.springframework.cloud

spring-cloud-starter-hystrix

org.springframework.cloud

spring-cloud-starter-hystrix-dashboard

org.springframework.boot

spring-boot-starter-actuator

监控地址

http://127.0.0.1:9001/hystrix; 打开网页

springboot集成hystrix熔断机制

在第一个输入框中输入

http://127.0.0.1:9001/hystrix.stream;

然后点击跳转按钮即可

springboot集成hystrix熔断机制

这样就OK了


分享到:


相關文章: