安装运行
下载地址:https://github.com/alibaba/Sentinel/releases
运行环境:
java 8 ;8080端口号不能被占用
通过java -jar ***.jar命令启动
访问http://localhost:8080(用户名密码都是sentinel)
初始化监控
搭建sentinel8401工程
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>cloud20</artifactId>
<groupId>com.atguigu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-sentinel-service8401</artifactId>
<dependencies>
<!-- alibaba nacos-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- 持久化 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!-- sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
</project>
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
#Nacos注册中心地址
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
management:
endpoints:
web:
exposure:
include: "*"
@SpringBootApplication
@EnableDiscoveryClient
public class SentinelMain8401 {
public static void main(String[] args) {
SpringApplication.run(SentinelMain8401.class);
}
}
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA() {
try {
TimeUnit.MILLISECONDS.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "----------testA";
}
@GetMapping("/testB")
public String testB() {
return "----------testB";
}
}
启动nacos和sentinel
访问http://localhost:8401/testA
即可观察到
流控规则
QPS(每秒钟的请求数量):当调用该api的QPS达到阈值的时候,进行限流。线程数:当调用该api的线程数达到剑值的时候,进行限流流控模式:
。直接: api达到限流条件时,直接限流
。关联:当关联的资源达到阈值时,就限流自己
。链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流)【api级别的针对来源】
1.直接失败
表示1s访问1次/testA则ok,超过1次报错
2.关联:(当B达到阀值则A则限流无法访问)
流控效果
1.预热
公式:阈值除以coldFactor(默认值为3),经过预热时长后才会达到阈值
5秒钟的时间从阀值从10/3慢慢过渡到10(应用场景,秒杀)
2.排队
服务降级
平均响应时间:
(0.2秒内如果没有处理完了/testD,而且1秒钟的请求数量>5 触发降级熔断时间为1s)
异常比例:(每秒请求>5且请求出错率大于80% ,时间窗口1s内触发熔断降级)
异常数:(访问异常超过5次,触发熔断)
热点Key限流
何为热点?热点即经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的 Top K 数据,并对其访问进行限制。比如:
商品 ID 为参数,统计一段时间内最常购买的商品 ID 并进行限制
用户 ID 为参数,针对一段时间内频繁访问的用户 ID 进行限制
热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看做是一种特殊的流量控制,仅对包含热点参数的资源调用生效。
https://github.com/alibaba/Sentinel/wiki(官网)
资源名指的是@SentinelResource(value = “testHotKey”)
参数索引:0指第一个请求参数,下面例子里面第一个请求参数 p1,第二请求参数p2
当testHotKey第一次参数请求QPS超过每秒1次,触发降级
@GetMapping("/testHotKey")
//value 必须唯一,可以随便写 ,blockHandler为降级方法
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2", required = false) String p2) {
return "-------testHotKey";
}
//降级方法
//当前方法的返回值和参数要跟原方法保持一致,但允许最后加入一个参数BlockException
public String deal_testHotKey(String p1, String p2,
BlockException exception){
return "----deal_testHotKey,o(╥﹏╥)o";
}
高级选项:
这里表示第一个请求参数值为5的时候QPS变成了200,其余情况下QPS为1
系统规则
对整个系统进行限流控制
SentilnelResource自定义报错方法
1.第一种
热点Key限流所演示的一样(缺陷,每个方法都要写一个兜底的方法)
2 统一兜底方法(必须是static)
3 统一兜底方法2
@Component
public class ExceptionHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
httpServletResponse.setContentType("application/json;charset=utf-8");
String message=null;
if (e instanceof FlowException) {
message ="限流异常";
} else if (e instanceof DegradeException) {
message = "降级异常";
} else if (e instanceof ParamFlowException) {
message = "参数限流异常";
} else if (e instanceof AuthorityException) {
message = "授权异常";
} else if (e instanceof SystemBlockException) {
message = "系统负责异常";
}
httpServletResponse.getWriter().write(JSON.toJSONString(message));
}
}
fallback
fallback管理运行异常(例如代码里面的java抛错),
blockHandler管理配置违规(例如限流)(如fallbck方法通过restTemplate远程掉用方法出现java异常则handlerFallback方法进行兜底处理),
如两个都进行配置,两个同时触发,则听blockHandler
整合feign
<!-- openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- SpringCloud alibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
#设置feign客户端超时时间(OpenFeign 默认支持ribbon) 默认超过1s没得到结果就报错
ribbon:
#指的是建立连接所用时间,适用于网络状况正常情况下,两端连接所用时间
ReadTimeout: 5000
#指的是连接建立后,从服务器获取到可用资源所用时间 5s钟
ConnectTimeout: 5000
#开启饥饿模式,一启动就从注册中心电渠服务进行缓存
eager-load:
enabled: true
#开启雪崩
feign:
hystrix:
enabled: true
如果是带了参数的接口,不管是被调用方还是调用方一定要带注解@RequestParam @RequestBody等,如不然会调用失败
@FeignClient(value = "nacos-payment-provider", fallback = PaymentFallbackServiceImpl.class)
public interface PaymentService {
@GetMapping(value = "/paymentSQL/{id}")
CommonResult<Payment> PaymentSQL(@PathVariable("id") Long id);
}
@Service
public class PaymentFallbackServiceImpl implements PaymentService {
@Override
public CommonResult<Payment> PaymentSQL(Long id) {
return new CommonResult<>(444444444, "服务降级返回,----PaymentFallbackServiceImpl", new Payment(id, "errorSerial"));
}
}
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84 {
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
规则持久化
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
#Nacos注册中心地址
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默认8719端口,假如被占用会自动从8719开始依次+1扫描,直至找到未被占用的端口
port: 8719
datasource:
dsl:
nacos:
server-addr: localhost:8848
dataId: cloudalibaba-sentinel-service
groupId: DEFAULT_GROUP
data_type: json
rule-type: flow
配置完成后启动项目发现
然后访问接口发现成功