文章目录
你的脸是为了呈现上帝赐给人类最贵重的礼物——微笑,一定要成为你工作最大的资产
雪崩问题及解决
简述
微服务中,服务间调用关系错综复杂,一个微服务往往依赖于多个其它微服务。
依赖服务I的业务请求被阻塞,用户不会得到响应,则tomcat的这个线程不会释放,于是越来越多的用户请求到来,越来越多的线程会阻塞:
服务器支持的线程和并发数有限,请求一直阻塞,会导致服务器资源耗尽,从而导致所有其它服务都不可用,那么当前服务也就不可用了。
那么,依赖于当前服务的其它服务随着时间的推移,最终也都会变的不可用,形成级联失败,雪崩就发生了:
解决雪崩问题
的常见方式有四种:
超时处理
•超时处理:设定超时时间,请求超过一定时间没有响应就返回错误信息
,不会无休止等待
熔断、限流
当发现访问服务D的请求异常比例过高时
,认为服务D有导致雪崩的风险,会拦截访问服务D的一切请求,形成熔断:
流量控制:限制业务访问的QPS,避免服务因流量的突增而故障
Sentinel入门
安装DashBoard
- 下载
- 运行
java -jar sentinel-dashboard-1.8.6.jar
- 如果要修改Sentinel的默认端口、账户、密码,可以通过下列配置:
| 配置项 | 默认值 | 说明 |
| -------------------------------- | ---------- | ---------- |
| server.port | 8080 | 服务端口 |
| sentinel.dashboard.auth.username | sentinel | 默认用户名 |
| sentinel.dashboard.auth.password | sentinel | 默认密码 |
例如,修改端口:
java -Dserver.port=8090 -jar sentinel-dashboard-1.8.6.jar
账号密码都是
sentinel
因为 还
没有
与微服务进行整合,所以为空
使用Sentinel
- pom依赖
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
- yaml
server:
port: 8088 # 微服务端口
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080 # dashboard的地址
- 随便访问一个接口
Fegin整合Sentinel
依赖
<!--fegin组件-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
开启对Sentinel的支持
feign:
sentinel:
enabled: true # 开启降级
创建容错类
@Component
public class ProductFeignFallBack implements ProductFeignApi {
@Override
public Product findByPid(Long pid) {
Product product = new Product ();
product.setPid (-1L);
product.setPname ("兜底数据");
product.setPprice (0.0);
return product;
}
}
在feign接⼝中 定义容错类
@FeignClient(name = "product-service", fallback =
ProductFeignFallBack.class)
public interface ProductFeignApi {
@RequestMapping("/product/{pid}")
public Product findByPid(@PathVariable("pid") Long pid);
}
feign接口指定fallback类,实现 Feign远程调用的接口,重写 方法即可!!!
集成Sentinel实现⽹关限流
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
规则持久化
引入依赖
在
需要限流的服务引入依赖
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
配置Nacos地址
在
需要限流的服务 配置地址
spring:
cloud:
sentinel:
transport:
dashboard: localhost:8080 # dashboard端口
datasource:
flow:
nacos:
server-addr: localhost:8848 # nacos地址
dataId: orderservice-flow-rules
groupId: SENTINEL_GROUP
rule-type: flow # 还可以是:degrade、authority、param-flow
见资料使用