Sentinel
Sentinel 是面向微服务的轻量级流量控制框架,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
Sentinel可以作为Hystrix的替代品,为系统提供服务熔断和服务降级的功能。
服务熔断:根据保险丝的熔断是一个原理,当调用目标服务大量超时和失败,这时候应该熔断掉该服务的调用,从而快速释放资源,这段时间所有对其调用都是快速返回,保证整体服务系统的稳定
服务降级:针对核心业务服务的压力剧增,根据当前业务场景和流量对其他非核心服务进行降级处理,可以进行限流,快速返回等处理,释放资源保证核心任务的正常运行。
第一步:部署sentinel-dashboard
sentinel-dashboard(点击下载jar包)是一个单独的应用,通过spring-boot进行启动,主要提供一个轻量级的控制台,它提供机器发现、单机资源实时监控、集群资源汇总,以及规则管理的功能。
这里可以理解为sentinel服务治理中心。
java -Dserver.port=18080 -jar sentinel-dashboard.jar
第二步:在项目中整合sentinel
注入依赖
<!--springCloud-Alibaba-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--sentinel限流-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
在application.properties中的相关配置
spring.application.name=imagerepair
server.port=8080
spring.cloud.sentinel.transport.dashboard=127.0.0.1:18080
spring.cloud.sentinel.eager=true
Controller层
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/hello")
public String hello(){
return userService.sayHello();
}
}
Service
@Service
public class UserService {
@SentinelResource(value = "sayHello",fallback = "sayHellofail")
public String sayHello(){
return "Hello,World";
}
public String sayHellofail(){
return "I'am sorry";
}
}
设置限流,快速访问,从而触发服务降级
QPS: QPS即每秒查询率,是对一个特定的查询服务器在规定时间内所处理流量多少的衡量标准
线程数:最大线程数, 在接收到请求且不拦截请求时,将当前工作线程数加1,完成一个请求之后将工作线程数减1,当当前工作线程数等于限流规则配置的最大线程数时,就可以拦截请求,抛出请求被限流的异常。
扫描二维码关注公众号,回复:
11480770 查看本文章
项目源码链接:https://github.com/luo948521848/JavaWebs/tree/master/springcloud%20sentinel