1.sentinel官網(wǎng)
1.2官網(wǎng)
https://github.com/alibaba/Sentinel
https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
下載源碼地址
image.png
1.2主要特性
image.png
1.3使用場(chǎng)景
https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring_cloud_alibaba_sentinel
服務(wù)使用中的各種問(wèn)題
服務(wù)雪崩赔癌;服務(wù)降級(jí);服務(wù)熔斷;服務(wù)限流
2.安裝Sentinel控制臺(tái)
2.1sentinel組件由2部分組成
image.png
2.2運(yùn)行環(huán)境
下載https://github.com/alibaba/Sentinel/releases (1.8v)
sentinel-dashboard-1.8.0.jar
java8環(huán)境块饺;
8080端口不能被占用(linux下開啟防火墻端口)
命令:java -jar sentinel-dashboard-1.8.0.jar
2.3訪問(wèn)sentinel管理界面:
http://localhost:8080(登錄賬號(hào)密碼均為sentinel)
image.png
3.初始化演示工程
啟動(dòng)Nacos8848成功
3.1創(chuàng)建module
cloudalibaba-sentinel-service8401
3.2POM依賴
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<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>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.6.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
3.3YML配置
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: 192.168.1.111:1111
sentinel:
transport:
dashboard: 192.168.1.111:8080
port: 8719 #默認(rèn)8719,假如被占用了會(huì)自動(dòng)從8719開始依次+1掃描芯杀。直至找到未被占用的端口
management:
endpoints:
web:
exposure:
include: '*'
3.4啟動(dòng)類
@EnableDiscoveryClient //nacos
@SpringBootApplication
public class MainApp8401
{
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class, args);
}
}
3.5業(yè)務(wù)類FlowLimitController
@RestController
public class FlowLimitController
{
@GetMapping("/testA")
public String testA() {
return "------testA";
}
@GetMapping("/testB")
public String testB() {
return "------testB";
}
}
啟動(dòng)Sentinel8080:java -jar sentinel-dashboard-1.8.0
啟動(dòng)微服務(wù)8401
啟動(dòng)8401微服務(wù)后查看sentienl控制臺(tái)
Sentinel采用的懶加載說(shuō)明:需要執(zhí)行一次調(diào)用http://localhost:8401/testA
sentinel8080正在監(jiān)控微服務(wù)8401
image.png
4.流控規(guī)則
4.1新增
image.png
image.png
4.2流控模式
4.2.1系統(tǒng)默認(rèn)
image.png
4.2.2測(cè)試
快速點(diǎn)擊訪問(wèn)http://localhost:8401/testA
Blocked by Sentinel (flow limiting)直接調(diào)用默認(rèn)報(bào)錯(cuò)信息(后續(xù)fallback的兜底方法)
image.png
4.3關(guān)聯(lián)
當(dāng)關(guān)聯(lián)的資源達(dá)到閾值時(shí)资铡,就限流自己
當(dāng)與A關(guān)聯(lián)的資源B達(dá)到閾值后,就限流自己
B惹事扣甲,A掛了
4.3.1配置
image.png
4.3.2測(cè)試
postman模擬并發(fā)密集訪問(wèn)testB
大批量線程高并發(fā)訪問(wèn)B,導(dǎo)致A失效了
4.4鏈路
多個(gè)請(qǐng)求調(diào)用了同一個(gè)微服務(wù)
4.4.1流控效果
默認(rèn)直接失敗齿椅,拋出異常(Blocked by Sentinel (flow limiting))
com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController
預(yù)熱
公式:閾值除以coldFactor(默認(rèn)值為3)琉挖,經(jīng)過(guò)預(yù)熱時(shí)長(zhǎng)后才會(huì)達(dá)到閾值
image.png
image.png
https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8
4.4.2源碼
com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController
4.4.3Warmup配置
image.png
多次點(diǎn)擊http://localhost:8401/testB,剛開始不行涣脚,后續(xù)慢慢OK
4.4.4排隊(duì)等待
image.png
勻速排隊(duì)示辈,閾值必須設(shè)置為QPS
image.png
com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController
5.降級(jí)規(guī)則
image.png
Sentinel的斷路器是沒(méi)有半開狀態(tài)的
半開的狀態(tài)系統(tǒng)自動(dòng)去檢測(cè)是否請(qǐng)求有異常,沒(méi)有異常就關(guān)閉斷路器恢復(fù)使用遣蚀,有異常則繼續(xù)打開斷路器不可用矾麻。具體可以參考Hystrix
5.1降級(jí)策略實(shí)戰(zhàn)RT
image.png
5.1.1測(cè)試
@GetMapping("/testD")
public String testD()
{
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
log.info("testD 測(cè)試RT");
return "------testD";
}
5.1.2配置
image.png
image.png
5.2異常比例
image.png
image.png
5.2.1測(cè)試代碼
@GetMapping("/testD")
public String testD()
{
log.info("testD 測(cè)試RT");
int age = 10/0;
return "------testD";
}
5.2.2配置
image.png
5.2.3結(jié)果
image.png
5.3異常數(shù)
image.png
image.png
異常數(shù)是按照分鐘統(tǒng)計(jì)的
5.3.1測(cè)試
@GetMapping("/testE")
public String testE()
{
log.info("testE 測(cè)試異常數(shù)");
int age = 10/0;
return "------testE 測(cè)試異常數(shù)";
}
image.png
5.4熱點(diǎn)key限流
官網(wǎng):https://github.com/alibaba/Sentinel/wiki/熱點(diǎn)參數(shù)限流
@SentinelResource
com.alibaba.csp.sentinel.slots.block.BlockException
5.4.1代碼
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1",required = false) String p1,
@RequestParam(value = "p2",required = false) String p2) {
//int age = 10/0;
return "------testHotKey";
}
//兜底方法
public String deal_testHotKey (String p1, String p2, BlockException exception){
return "------deal_testHotKey,o(╥﹏╥)o";
}
5.4.2配置
image.png
1.@SentinelResource(value = "testHotKey")
異常打到了前臺(tái)用戶界面看不到,不友好
2.@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
方法testHostKey里面第一個(gè)參數(shù)只要QPS超過(guò)每秒1次芭梯,馬上降級(jí)處理次乓,用了我們自己定義的
error
http://localhost:8401/testHotKey?p1=abc
http://localhost:8401/testHotKey?p1=abc&p2=33
right
http://localhost:8401/testHotKey?p2=abc
5.5參數(shù)例外項(xiàng)
上述案例演示了第一個(gè)參數(shù)p1,當(dāng)QPS超過(guò)1秒1次點(diǎn)擊后馬上被限流
特殊情況
我們期望p1參數(shù)當(dāng)它是某個(gè)特殊值時(shí)皆辽,它的限流值和平時(shí)不一樣
假如當(dāng)p1的值等于5時(shí),它的閾值可以達(dá)到200
5.5.1配置
image.png
5.5.2測(cè)試
http://localhost:8401/testHotKey?p1=5當(dāng)p1等于5的時(shí)候,閾值變?yōu)?00
http://localhost:8401/testHotKey?p1=3當(dāng)p1不等于5的時(shí)候轰胁,閾值就是平常的1
6系統(tǒng)規(guī)則
image.png
6.1配置全局QPS
@SentinelResource
按資源名稱限流+后續(xù)處理
啟動(dòng)Nacos成功,啟動(dòng)Sentinel成功
Module:cloudalibaba-sentinel-service8401
6.1.1POM
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
6.1.2YML
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719 #默認(rèn)8719手蝎,假如被占用了會(huì)自動(dòng)從8719開始依次+1掃描局蚀。直至找到未被占用的端口
management:
endpoints:
web:
exposure:
include: '*'
6.1.3業(yè)務(wù)類RateLimitController
@RestController
public class RateLimitController
{
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource()
{
return new CommonResult(200,"按資源名稱限流測(cè)試OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception)
{
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服務(wù)不可用");
}
主啟動(dòng)后
@EnableDiscoveryClient
@SpringBootApplication
public class MainApp8401
{
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class, args);
}
}
6.2配置流控規(guī)則
6.2.1配置步驟
image.png
圖形配置和代碼關(guān)系
表示1秒鐘內(nèi)查詢次數(shù)大于1彻桃,就跑到我們自定義的處流,限流
6.2.2測(cè)試
1秒鐘點(diǎn)擊1下澎媒,OK
超過(guò)上述問(wèn)題搞乏,瘋狂點(diǎn)擊,返回了自己定義的限流處理信息戒努,限流發(fā)送
按照Url地址限流+后續(xù)處理
通過(guò)訪問(wèn)的URL來(lái)限流查描,會(huì)返回Sentinel自帶默認(rèn)的限流處理信息
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl()
{
return new CommonResult(200,"按url限流測(cè)試OK",new Payment(2020L,"serial002"));
}
image.png
瘋狂點(diǎn)擊http://localhost:8401/rateLimit/byUrl
會(huì)返回sentinel自帶的限流處理結(jié)果
上面兜底方法面臨的問(wèn)題
image.png
6.3客戶自定義限流處理邏輯
6.3.1創(chuàng)建customerBlockHandler類用于自定義限流處理邏輯
public class CustomerBlockHandler {
public static CommonResult handleException(BlockException exception) {
return new CommonResult(2020, "自定義限流處理信息....CustomerBlockHandler");
}
}
6.3.2RateLimitController
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客戶自定義",new Payment(2020L,"serial003"));
}
6.3.3啟動(dòng)微服務(wù)后先調(diào)用一次
http://localhost:8401/rateLimit/customerBlockHandler
6.3.4配置
image.png
7.服務(wù)熔斷功能
7.1概述
sentinel整合ribbon+openFeign+fallback
7.2Ribbon系列
新建消費(fèi)者cloudalibaba-provider-payment9003/9004
7.2.1POM
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><!-- 引入自己定義的api通用包,可以使用Payment支付Entity -->
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<!-- SpringBoot整合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>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
7.2.2YML
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
7.2.3啟動(dòng)類
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003
{
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class, args);
}
}
7.2.4業(yè)務(wù)類
@RestController
public class PaymentController
{
@Value("${server.port}")
private String serverPort;
public static HashMap<Long, Payment> hashMap = new HashMap<>();
static{
hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
}
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort: "+serverPort,payment);
return result;
}
}
7.2.5新建消費(fèi)者84
cloudalibaba-consumer-nacos-order84
7.2.6POM
<?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>cloud2020</artifactId>
<groupId>com.atguigu.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-consumer-nacos-order84</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
7.2.6YML
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
7.2.7主啟動(dòng)類
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84
{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
7.2.8業(yè)務(wù)類
ApplicationContextConfig
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
CircleBreakerController的全部源碼
@RestController
@Slf4j
public class CircleBreakerController {
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@RequestMapping("/consumer/fallback/{id}")
//@SentinelResource(value = "fallback") //沒(méi)有配置
//@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只負(fù)責(zé)業(yè)務(wù)異常
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只負(fù)責(zé)sentinel控制臺(tái)配置違規(guī)
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler",
exceptionsToIgnore = {IllegalArgumentException.class})
public CommonResult<Payment> fallback(@PathVariable Long id) {
CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/"+id, CommonResult.class,id);
if (id == 4) {
throw new IllegalArgumentException ("IllegalArgumentException,非法參數(shù)異常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,該ID沒(méi)有對(duì)應(yīng)記錄,空指針異常");
}
return result;
}
//fallback
public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底異常handlerFallback,exception內(nèi)容 "+e.getMessage(),payment);
}
//blockHandler
public CommonResult blockHandler(@PathVariable Long id,BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,無(wú)此流水: blockException "+blockException.getMessage(),payment);
}
}
fallback管運(yùn)行異常
blockHandler管配置違規(guī)
7.2.8測(cè)試地址
http://localhost:84/consumer/fallback/1給客戶error頁(yè)面,不友好
fallback和blockHandler都配置
image.png
7.3Feign系列
7.3.1POM
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
7.3.2YML
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
service-url:
nacos-user-service: http://nacos-payment-provider
#對(duì)Feign的支持
feign:
sentinel:
enabled: true
7.3.3業(yè)務(wù)類
帶@FeignClient注解的業(yè)務(wù)接口
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService
{
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
fallback = PaymentFallbackService.class
PaymentFallbackService實(shí)現(xiàn)類
@Component
public class PaymentFallbackService implements PaymentService
{
@Override
public CommonResult<Payment> paymentSQL(Long id)
{
return new CommonResult<>(44444,"服務(wù)降級(jí)返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
controller
// OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
添加@EnableFeignClients啟動(dòng)Feign的功能
@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class OrderNacosMain84
{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class, args);
}
}
http://lcoalhost:84/consumer/paymentSQL/1
測(cè)試84調(diào)用9003冬三,此時(shí)故意關(guān)閉9003微服務(wù)提供者匀油,看84消費(fèi)側(cè)自動(dòng)降級(jí),不會(huì)被耗死
7.4規(guī)則持久化
一旦我們重啟應(yīng)用勾笆,Sentinel規(guī)則將消失敌蚜,生產(chǎn)環(huán)境需要將配置規(guī)則進(jìn)行持久化
將限流配置規(guī)則持久化進(jìn)Nacos保存,只要刷新8401某個(gè)rest地址窝爪,sentinel控制臺(tái)的流控規(guī)則就能看到弛车,只要Nacos里面的配置不刪除,針對(duì)8401上Sentinel上的流控規(guī)則持續(xù)有效
7.4.1步驟
修改cloudalibaba-sentinel-service8401
POM
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
YML
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848 #Nacos服務(wù)注冊(cè)中心地址
sentinel:
transport:
dashboard: localhost:8080 #配置Sentinel dashboard地址
port: 8719
datasource: #添加Nacos數(shù)據(jù)源配置
ds1:
nacos:
server-addr: localhost:8848
dataId: cloudalibaba-sentinel-service
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include: '*'
feign:
sentinel:
enabled: true # 激活Sentinel對(duì)Feign的支持
7.4.2添加Nacos業(yè)務(wù)規(guī)則配置
image.png
image.png
7.4.3啟動(dòng)8401后刷新sentinel發(fā)現(xiàn)業(yè)務(wù)規(guī)則有了
image.png