第一步:導(dǎo)入依賴
工程搭建參考上一節(jié)gateway入門,sentinel也是在此基礎(chǔ)上搭建的。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
第二步:配置yml
server:
port: 9999
spring:
application:
name: sentinel-gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080 #sentinel的圖形化界面訪問路徑
scg:
fallback: #服務(wù)降級返回的響應(yīng)結(jié)果
mode: reponse
response-status: 426
response-body: error request
gateway:
discovery:
locator:
enabled: false #開啟表示根據(jù)微服務(wù)名稱映射,就是微服務(wù)名稱拼接到url中可以直接訪問,但是不推薦這么使用 容易暴露微服務(wù)
# enabled: false #默認(rèn)開啟網(wǎng)關(guān)true,關(guān)閉網(wǎng)關(guān)false
第三步:啟動網(wǎng)關(guān)
此時啟動網(wǎng)關(guān)后我們就完成整合了,但是如何使用呢。
第四步:如何使用sentinel限流
首先下載sentinel dashboard監(jiān)控管理頁面的jar包,官網(wǎng)下載https://github.com/alibaba/Sentinel/releases/tag/v1.8.0,我這里使用v1.7版本

在cmd中運(yùn)行java -jar D:\software\sentinel-dashboard-1.7.0后面跟上你的文件路徑,可能會出錯

我運(yùn)行1.6jar包直接報錯,更換1.7jar包后運(yùn)行正常,一旦運(yùn)行成功后,關(guān)閉后再次運(yùn)行也會出錯,所以我右擊打開方式,選擇Java(TM) Platform SE binary運(yùn)行,任務(wù)管理器就會有這個服務(wù),總之就是要運(yùn)行編譯這個jar包服務(wù)

然后訪問是可以的賬號密碼都是sentinel,登錄

一片空白

此時網(wǎng)關(guān)已經(jīng)啟動,我們隨便掉一個接口返回成功即可,因為sentinel是懶加載的,需要請求來觸發(fā)它。

此時就有了網(wǎng)關(guān)服務(wù)

用route id方式配置限流規(guī)則


其中order-center為yml中 routes的id,表示對這個微服務(wù)進(jìn)行限流
spring:
cloud:
gateway:
routes:
- id: order-center #id必須要唯一
uri: lb://order-center
predicates:
- Path=/order/**
- id: product-center #id必須要唯一
uri: lb://product-center
#謂詞工廠
predicates:
- Path=/product/** #先匹配斷言 然后追加或省略前綴
我們網(wǎng)頁發(fā)起請求,點擊請求一次,請求成功

我們一秒快速點擊發(fā)起多次請求

請求太多會失敗,每秒只允許一個請求,返回我們定義的降級狀態(tài)碼426

用api分組方式配置限流
先創(chuàng)建分組

然后這里就有了分組選擇項


快速發(fā)起多次請求效果是一樣的

總結(jié):一旦項目重啟sentinel中我們的這些配置都將消失,因為沒有持久化,以上就是sentinel整合網(wǎng)關(guān)的簡單應(yīng)用。