SpringCloud Alibaba Sentinel實(shí)現(xiàn)熔斷與限流
點(diǎn)擊上方藍(lán)色字體,選擇“標(biāo)星公眾號(hào)”
優(yōu)質(zhì)文章,第一時(shí)間送達(dá)
作者 | C紫楓
來(lái)源 | urlify.cn/f2MvAf
概述
簡(jiǎn)單來(lái)說(shuō)是histrix的升級(jí)版,也是替換的新組件。
官網(wǎng):https://github.com/alibaba/Sentinel
中文官網(wǎng):https://github.com/alibaba/Sentinel/wiki/介紹
下載地址:https://github.com/alibaba/Sentinel/releases
安裝Sentiel控制臺(tái)
運(yùn)行命令:java -jar sentinel-dashboard-1.7.0.jar
訪(fǎng)問(wèn)sentinel管理界面:http://localhost:8080(登錄賬號(hào)密碼均為sentinel)
初始化演示功能cloudalibaba-sentinel-service8401
pom.xml
<!--SpringCloud ailibaba sentinel-datasource-nacos 后續(xù)做持久化用到-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
application.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:
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的支持
啟動(dòng)類(lèi)
package com.czf.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class MainApp8401 {
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class,args);
}
}
業(yè)務(wù)類(lèi)FlowLimitController----限流
@SentinelResource的blockHandler的屬性開(kāi)啟兜底方法
package com.czf.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
/**
* @auther czf
* @create 2020-02-24 16:26
* 限流
*/
@RestController
@Slf4j
public class FlowLimitController
{
@GetMapping("/testA")
public String testA()
{
return "------testA";
}
@GetMapping("/testB")
public String testB()
{
log.info(Thread.currentThread().getName()+"\t"+"...testB");
return "------testB";
}
@GetMapping("/testD")
public String testD()
{
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
log.info("testD 測(cè)試RT");
/* log.info("testD 異常比例");
int age = 10/0;*/
return "------testD";
}
@GetMapping("/testE")
public String testE()
{
log.info("testE 測(cè)試異常數(shù)");
int age = 10/0;
return "------testE 測(cè)試異常數(shù)";
}
@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"; //sentinel系統(tǒng)默認(rèn)的提示:Blocked by Sentinel (flow limiting)
}
}
自定義兜底類(lèi):CustomerBlockHandler
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler()
{
return new CommonResult(200,"按客戶(hù)自定義",new Payment(2020L,"serial003"));
}
}
package com.czf.springcloud.myhandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.czf.springcloud.entities.CommonResult;
/**
* @auther zzyy
* @create 2020-02-25 15:32
*/
public class CustomerBlockHandler
{
public static CommonResult handlerException(BlockException exception)
{
return new CommonResult(4444,"按客戶(hù)自定義,global handlerException----1");
}
public static CommonResult handlerException2(BlockException exception)
{
return new CommonResult(4444,"按客戶(hù)自定義,global handlerException----2");
}
}
流控規(guī)則

流控模式

1.直接(默認(rèn))


2.關(guān)聯(lián)
當(dāng)關(guān)聯(lián)的資源達(dá)到閾值時(shí),就限流自己。
3.鏈路
多個(gè)請(qǐng)求調(diào)用同一個(gè)微服務(wù)
流控效果
直接->快速失敗(默認(rèn)的流控處理)
直接失敗,拋出異常。Blocked by Sentinel(flow limiting)
預(yù)熱
說(shuō)明:公式:閾值除以coldFactor(默認(rèn)值為3),經(jīng)過(guò)預(yù)熱時(shí)長(zhǎng)后才會(huì)達(dá)到閾值
官網(wǎng):
默認(rèn)coldFactor為3,即請(qǐng)求QPS從threshold/3開(kāi)始,經(jīng)預(yù)熱時(shí)長(zhǎng)逐漸升至設(shè)定的QPS閾值
WarmUp配置:
效果:多次點(diǎn)擊http://localhost:8401/testB,剛開(kāi)始不行,后續(xù)慢慢OK
應(yīng)用場(chǎng)景:如:秒殺系統(tǒng)在開(kāi)啟瞬間,會(huì)有很多流量上來(lái),很可能把系統(tǒng)打死,預(yù)熱方式就是為了保護(hù)系統(tǒng),可慢慢的把流量放進(jìn)來(lái),慢慢的把閾值增長(zhǎng)到設(shè)置的閾值。
排隊(duì)等待

勻速排隊(duì),閾值必須設(shè)置為QPS
降級(jí)規(guī)則
熔斷之后就會(huì)降級(jí)(給出錯(cuò)誤消息提示)
官網(wǎng):https://github.com/alibaba/Sentinel/wiki/熔斷降級(jí)
基本介紹:QPS >=5且比例(秒級(jí)統(tǒng)計(jì))超過(guò)閾值時(shí),觸發(fā)降級(jí),時(shí)間窗口結(jié)束后,關(guān)閉降級(jí)

降級(jí)策略實(shí)戰(zhàn)
1.RT
該請(qǐng)求需要1秒來(lái)完成,當(dāng)RT(平均響應(yīng)時(shí)間)為200毫秒,1秒遠(yuǎn)大于RT閾值。
@GetMapping("/testD")
public String testD()
{
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
log.info("testD 測(cè)試RT");
/* log.info("testD 異常比例");
int age = 10/0;*/
return "------testD";
}


2.異常比例
3.異常數(shù)
@GetMapping("/testE")
public String testE()
{
log.info("testE 測(cè)試異常數(shù)");
int age = 10/0;
return "------testE 測(cè)試異常數(shù)";
}


熱點(diǎn)key限流



@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"; //sentinel系統(tǒng)默認(rèn)的提示:Blocked by Sentinel (flow limiting)
}

當(dāng)?shù)谝粋€(gè)參數(shù)超過(guò)設(shè)置的閾值(1)就會(huì)降級(jí)報(bào)錯(cuò)
參數(shù)例外項(xiàng)



其他
手賤添加異常看看o(╥﹏╥)o

系統(tǒng)規(guī)則

官網(wǎng)介紹:https://github.com/alibaba/Sentinel/wiki/系統(tǒng)自適應(yīng)限流

不合適,使用危險(xiǎn),一竹竿打死一船人
@SentinelResource
按資源名稱(chēng)限流+后續(xù)處理
@GetMapping("/byResource")
@SentinelResource(value = "byResource",blockHandler = "handleException")
public CommonResult byResource()
{
return new CommonResult(200,"按資源名稱(chēng)限流測(cè)試OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException exception)
{
return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服務(wù)不可用");
}


按照Url地址限流+后續(xù)處理
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")//url和這里的value都可以配置流控等,但必須唯一。value的值是資源名
public CommonResult byUrl() {
return new CommonResult(200, "按url限流測(cè)試OK", new Payment(2020L, "serial002"));
}


客戶(hù)自定義限流處理邏輯

RateLimitController
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
blockHandlerClass = CustomerBlockHandler.class,
blockHandler = "handlerException2")
public CommonResult customerBlockHandler() {
return new CommonResult(200, "按客戶(hù)自定義", new Payment(2020L, "serial003"));
}
CustomerBlockHandler
public class CustomerBlockHandler
{
public static CommonResult handlerException(BlockException exception)
{
return new CommonResult(4444,"按客戶(hù)自定義,global handlerException----1");
}
public static CommonResult handlerException2(BlockException exception)
{
return new CommonResult(4444,"按客戶(hù)自定義,global handlerException----2");
}
}


更多注解說(shuō)明
官網(wǎng):https://github.com/alibaba/Sentinel/wiki/注解支持
Sentinel主要有三個(gè)核心Api:
1.sphU定義資源
2.Tracer定義統(tǒng)計(jì)
3.ContextUtil定義了上下文
服務(wù)熔斷功能
sentinel整合ribbon+openFeign+fallback
消費(fèi)者84
提供者:9003、9004

cloudalibaba-consumer-nacos-order84(消費(fèi)者)
pom.xml
<!--SpringCloud openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!--SpringCloud ailibaba sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
application.yml
server:
port: 84
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
#配置Sentinel dashboard地址
dashboard: localhost:8080
#默認(rèn)8719端口,假如被占用會(huì)自動(dòng)從8719開(kāi)始依次+1掃描,直至找到未被占用的端口
port: 8719
#消費(fèi)者將要去訪(fǎng)問(wèn)的微服務(wù)名稱(chēng)(注冊(cè)成功進(jìn)nacos的微服務(wù)提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
# 激活Sentinel對(duì)Feign的支持
feign:
sentinel:
enabled: true
CircleBreakerController(ribbon/openFeign)
fallback管運(yùn)行異常(例如空指針異常之類(lèi)的);blockHandler管配置違規(guī)(超過(guò)閾值之類(lèi)的)
package com.czf.springcloud.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.czf.springcloud.entities.CommonResult;
import com.czf.springcloud.entities.Payment;
import com.czf.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
/**
* @auther zzyy
* @create 2020-02-25 16:05
*/
@RestController
@Slf4j
public class CircleBreakerController
{
//----------------------------------ribbon----restTemplate
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ùn)行異常,兜底,相當(dāng)于服務(wù)降級(jí)
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只負(fù)責(zé)sentinel控制臺(tái)配置違規(guī),違規(guī)兜底---主管配置違規(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);
}
//==================OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id)
{
return paymentService.paymentSQL(id);
}
}
ribbon的配置
package com.czf.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* ribbon的負(fù)載均衡
*/
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
OpenFeign配置
package com.czf.springcloud.service;
import com.czf.springcloud.entities.CommonResult;
import com.czf.springcloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
*openFeign
*/
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentService
{
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
運(yùn)行異常配置
package com.czf.springcloud.service;
import com.czf.springcloud.entities.CommonResult;
import com.czf.springcloud.entities.Payment;
import org.springframework.stereotype.Component;
/**
* openFeign
*/
@Component
public class PaymentFallbackService implements PaymentService
{
@Override
public CommonResult<Payment> paymentSQL(Long id)
{
return new CommonResult<>(44444,"服務(wù)降級(jí)返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
cloudalibaba-provider-payment9004
pom.xml
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
application.yml
server:
port: 9004
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
PaymentController
package springcloud.controller;
import com.czf.springcloud.entities.CommonResult;
import com.czf.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
/**
* @auther zzyy
* @create 2020-02-25 16:11
*/
@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;
}
}
2者同時(shí)配置,達(dá)到配置閾值只會(huì)報(bào)blockHandler對(duì)應(yīng)兜底方法的返回值信息
規(guī)則持久化
存在的問(wèn)題
一旦我們重啟應(yīng)用,sentinel規(guī)則消失,生產(chǎn)環(huán)境需要將配置規(guī)則進(jìn)行持久化。
怎么實(shí)現(xiàn)?
將限流規(guī)則持久進(jìn)Nacos保存,只要刷新8401某個(gè)rest地址,sentinel控制臺(tái)的流控規(guī)則就能看得到,只要Nacos里面的配置不刪除,針對(duì)8401上的流控規(guī)則持續(xù)有效
cloudalibaba-sentinel-service8401
pom.xml
<!-- sentinel-datasource-nacos 后續(xù)持久化用 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
application.yml


添加Nacos業(yè)務(wù)規(guī)則配置

[
{
"resource":"/rateLimit/byUrl",
"limitApp":"default",
"grade":1,
"count":1,
"strategy":0,
"controlBehavior":0,
"clusterMode":false
}
]

啟動(dòng)8401刷新sentinel發(fā)現(xiàn)業(yè)務(wù)規(guī)則變了
測(cè)試接口:http://localhost:8401/rateLimit/byUrl
鋒哥最新SpringCloud分布式電商秒殺課程發(fā)布
??????
??長(zhǎng)按上方微信二維碼 2 秒
感謝點(diǎn)贊支持下哈 
