hystrix超详细教学
1、什么是hystrix?
是一个做熔断的框架,当程序被高并发访问时可能会造成微服务的宕机,hystrix可以熔断微服务之间通信。防止后台服务发生雪崩。
2、Hystrix作用
- 熔断
- 查看微服务请求状态
3、Hystrix使用场景
是在微服务架构下才有意义,做各个微服务通信熔断的。
- 并发和负载量如果都不大,可用可不用,一旦负载过大,一定要用熔断。
- 看业务需求,如果对熔断的需求比较简单,选用Hystrix,如果需求复杂,可用选用sentinel(sentinel功能比较丰富,比如限流,比如可以设置服务器限流,一秒钟只处理多少个请求,超过这个请求熟练的 ,就自动熔断了)。
4、准备工作
【1.启动nacos和redis】
【2.以openfeign代码为例子】
openfeign-Score工程(没有代码改变)先启动之后断开(模拟宕机),
openfeign-User工程(修改一下工程的注册名字就可以)。
spring.application.name=hystrixdemo
运行效果:
【开启Score工程:】
【关闭Score工程】
5、应用
1、引入依赖
在User工程里添加下面的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2、开启Hystrix
在User工程的启动类上添加开启Hystrix的注解
@EnableHystrix
此时完成上述两个操作后,再次关闭Score工程,页面也是报错,但不是“连接超时”的错误,而是“熔断类型”的错误。为了让用户体验度好一些,报错信息不暴露给用户,我们完成下面的编码。
3、添加熔断
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import lombok.Setter;
import org.jsoft.demo.dto.UserDto;
import org.jsoft.demo.service.IUserService;
import org.jsoft.demo.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author szsw
* @date 2024/4/12 8:06:07
*/
@RestController
@RequestMapping("/user")
@Setter
public class UserController {
@Autowired
private IUserService userService;
@GetMapping
@HystrixCommand(fallbackMethod = "infoHystrix") //一旦熔断了,就去执行infoHystrix方法。
public Result info() {
User user = userService.info();
return Result.ok().put("data", user);
}
public Result infoHystrix() {
return Result.error().setMessage("被熔断了");
}
}
如果发生了熔断,那么执行注解中fallbackMethod定义的方法。
配置文件
feign:
hystrix:
enabled: true
开启feign的hystrix做熔断,默认是开启的,需要知道有这个配置,在开发中可能会用到。
【连接成功:】
【连接失败】
6、添加仪表盘【了解,功能单一使用少】
添加依赖
在user工程里添加如下依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
添加配置类
在user工程里添加如下配置类:直接粘贴就可以,是固定写法。
import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServlet;
@Configuration
public class HystrixConfig {
@Bean
public ServletRegistrationBean<HttpServlet> httpServletServletRegistrationBean() {
ServletRegistrationBean<HttpServlet> result = new ServletRegistrationBean<>(new HystrixMetricsStreamServlet());
result.addUrlMappings("/actuator/hystrix.stream");
return result;
}
}
启动类添加注解@EnableHystrixDashboard
启动项目,访问如下地址
地址1:http://localhost:100/actuator/hystrix.stream
地址2:http://localhost:100/hystrix
第一个地址是用来在仪表盘中配置的,第二个地址是访问仪表盘的。
在访问仪表盘之前先访问一下接口,Hystrix是懒加载,不访问接口第一个请求地址会一直输出ping