一、什么是Sentinel?
随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
Sentinel 的主要特性:
二、整合Sentinel
1、导入依赖
<!--alibaba cloud Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
2、下载控制台
下载
查看版本
启动
java -jar sentinel-dashboard-1.6.3.jar --server.port=8858
访问 http://localhost:8858/#/dashboard/home
默认账号和密码都是 sentinel。
3、配置控制台地址信息
spring:
datasource:
username: root
password: root
url: jdbc:mysql://192.168.10.10:3306/gulimall_oms
driver-class-name: com.mysql.cj.jdbc.Driver
# 配置nacos注册中心
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
# sentinel控制台地址配置
sentinel:
transport:
port: 8719
dashboard: localhost:8333
application:
name: gulimall-order
thymeleaf:
cache: false # 测试期间关掉缓存
redis:
host: 192.168.10.10
prot: 6379
session:
store-type: redis # Session store type,SpringSession整合,使用redis作为session存储
mybatis-plus:
mapper-location: classpath:/mapper/**/*.xml
global-config:
db-config:
id-type: auto # id主键自增
server:
port: 9000
servlet:
session:
timeout: 30m # Session timeout,SpringSession整合
三、导入信息审计模块actuator
导入actuator依赖
actuator 审计模块,可以实时统计Springboot健康状态,包括整个请求的调用信息等,Sentinel通过统计拿到的这些信息最终做整个数据的监控功能能。
!-- 审计信息模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
暴露端口:
每一个微服务都导入 actuator,并配合 management.endpoints.web.exposure.include=*
,暴露端口之后别人就能访问了。
# === Sentinel ===
# 暴露端口,别人就可以访问了
management:
endpoints:
web:
exposure:
include: "*"
Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、当前实例的 IP,Sentinel Dashboard 地址,Block Page,应用与 Sentinel Dashboard 的心跳频率等等信息。
IDEA编辑器可以实时统计springboot健康及请求信息:
四、自定义 Sentinel流控返回数据
package com.atguigu.gulimall.order.config;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
/**
* Sentinel自定义阻塞返回方法
*
* @author: kaiyi
* @createTime: 2020-09-17 16:05
**/
@Configuration
public class GulimallOrderSentinelConfig {
public GulimallOrderSentinelConfig() {
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getMsg());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(error));
}
});
}
}
1.8版本后
package com.kun.auth.config;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.kun.common.exception.BizCodeEnum;
import com.kun.common.utils.R;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Sentinel自定义阻塞返回方法
*
* @author: kaiyi
* @createTime: 2020-09-17 16:05
**/
@Configuration
public class BlockSentinelConfig implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
R error = R.error(BizCodeEnum.TOO_MANY_REQUEST.getCode(), BizCodeEnum.TOO_MANY_REQUEST.getMsg());
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.getWriter().write(JSON.toJSONString(error));
}
}
设置控流
QPS设置为3,即每秒最多请求3个,如果超过会由Sentinel直接返回流量过大信息:
狂刷新页面
实时监控
五、熔断降级
- 1)、调用方的熔断保护,
feign.sentinel.enabled=true
- 2)、调用方手动指定远程服务的降级策略(在 sentinel管理后台配置),远程服务被降级处理,触发我们的熔断回调方法。
- 3)、超大流量的时候,必须牺牲一些远程服务,在服务的提供方(远程服务)指定降级策略。
提供方是在运行,但是不运行自己的业务逻辑,返回的是默认的降级数据(限流的数据)
配置
feign.sentinel.enabled=true
远程调用熔断
@FeignClient(value = "gulimall-seckill",fallback= SeckillFeignServiceImpl.class)
六、网关流控
<!-- sentinel网关流控 -->
<!-- https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
xml配置
server:
port: 88
spring:
profiles:
active: dev
application:
name: gulimall-gatway
cloud:
nacos:
discovery:
server-addr: localhost:8848 #设置nacos地址
config:
server-addr: localhost:8848 #设置nacos地址
gateway:
discovery:
locator:
enabled: true #开启从注册中心的动态路由功能,利用服务名进行路由
lower-case-service-id: true
routes:
- id: test-route1
uri: https://www.bilibili.com
predicates:
- Query=url,bilibili
- id: test-route2
uri: https://www.qq.com
predicates:
- Query=url,qq
-
sentinel:
transport:
port: 8719
dashboard: localhost:8858
# 服务启动直接建立心跳连接
eager: true
#添加如下配置,可观察到一些请求细节:
logging:
level:
org.springframework.cloud.gateway: trace
org.springframework.http.server.reactive: debug
org.springframework.web.reactive: debug
reactor.ipc.netty: debug
# === Sentinel ===
# 暴露端口,别人就可以访问了
management:
endpoints:
web:
exposure:
include: "*"
定制网关流控配置:
package com.atguigu.gulimall.gateway.config;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* Sentinel网关限流回调配置
*
* @author: kaiyi
* @create: 2020-09-18 00:21
*/
@Configuration
public class SentinelGatewayConfig {
public SentinelGatewayConfig(){
GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
/**
* 网关限流了请求,就会调用此回调
* Mono Flux
* @param serverWebExchange
* @param throwable
* @return
*/
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
R error = R.error(BizCodeEnum.TOO_MANY_REQUEST.getCode(), BizCodeEnum.TOO_MANY_REQUEST.getMsg());
String errJson = JSON.toJSONString(error);
Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(errJson), String.class);
return body;
}
});
}
}