国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由維度、API維度進(jìn)行流控

這篇具有很好參考價(jià)值的文章主要介紹了SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由維度、API維度進(jìn)行流控。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

Gateway整合Sentinel

? 前面使用過Sentinel組件對(duì)服務(wù)提供者、服務(wù)消費(fèi)者進(jìn)行流控、限流等操作。除此之外,Sentinel還支持對(duì)Gateway、Zuul等主流網(wǎng)關(guān)進(jìn)行限流。

? 自sentinel1.6.0版開始,Sentinel提供了Gateway的適配模塊,能針對(duì)路由(route)和自定義API分組兩個(gè)維度進(jìn)行限流。

路由維度

路由維度是指配置文件中的路由條目,資源名是對(duì)應(yīng)的routeId,相比自定義API維度,這是比較粗粒度的??聪氯绾螌?shí)現(xiàn):

  1. 導(dǎo)入Sentinel組件為Gateway提供的適配依賴包,在pom.xml中導(dǎo)入依賴

    <!--sentinel為gateway提供的適配包-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    </dependency>
    
  2. 增加配置類SentinelRouteConfiguration,實(shí)例化SentinelGatewayFilterSentinelBlockExceptionHandler對(duì)象,初始化限流規(guī)則

    @Configuration  // 配置類
    public class SentinelRouteConfiguration {   // 路由限流規(guī)則配置類
    
        private final List<ViewResolver> viewResolvers;
    
        private final ServerCodecConfigurer serverCodecConfigurer;
    
    
        public SentinelRouteConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @PostConstruct
        public void initGatewayRules() {    // 初始化限流規(guī)則
            Set<GatewayFlowRule> rules = new HashSet<>();
            GatewayFlowRule gatewayFlowRule = new GatewayFlowRule("user_route");    // 資源名(gateway中的路由id)
            gatewayFlowRule.setCount(1);    // 限流閾值
            gatewayFlowRule.setIntervalSec(1);  // 統(tǒng)計(jì)時(shí)間窗口,默認(rèn)1s
    
            rules.add(gatewayFlowRule);
            GatewayRuleManager.loadRules(rules);    // 載入規(guī)則
        }
    
        @PostConstruct
        public void initBlockHandlers() {    // 限流后的響應(yīng)
            BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
                Map<String, Object> result = new HashMap<>();
                result.put("code", "0");
                result.put("message", "您已被限流");
                return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(result));
            };
    
            GatewayCallbackManager.setBlockHandler(blockRequestHandler);    // 設(shè)置限流響應(yīng)
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
            return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter sentinelGatewayFilter() {   // 初始化限流過濾器
            return new SentinelGatewayFilter();
        }
    
    }
    

    注意:Gateway限流是通過Filter實(shí)現(xiàn)的,主要是注入SentinelGatewayFilter實(shí)例和SentinelGatewayBlockExceptionHandler實(shí)例

  3. 在yml中,設(shè)置兩個(gè)route,user_routeshop_route,上面主要是對(duì)user_route限流了,著重看下

    server:
      port: 8083
    
    spring:
      application:
        name: gateway   # 服務(wù)名
    
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848 # nacos地址
        gateway:
          routes: # 路由,可配置多個(gè)
          - id: user_route  # 路由id,唯一即可,默認(rèn)UUID
            uri: lb://user  # 路由地址(匹配成功后的服務(wù)地址) user是用戶服務(wù)的服務(wù)名稱
            order: 1  # 路由優(yōu)先級(jí),默認(rèn)0,越低優(yōu)先級(jí)越高
            predicates:
            - Path=/user/**   # 斷言,匹配規(guī)則
    
          - id: shop_route  # 路由id,唯一即可,默認(rèn)UUID
            uri: lb://shop  # 路由地址(匹配成功后的服務(wù)地址) shop是用戶服務(wù)的服務(wù)名稱
            order: 1  # 路由優(yōu)先級(jí),默認(rèn)0,越低優(yōu)先級(jí)越高
            predicates:
            - Path=/shop/**   # 斷言,匹配規(guī)則
    
  4. 啟動(dòng)服務(wù)開始調(diào)試

    SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由維度、API維度進(jìn)行流控,SpringCloud,SpringBoot,Java,gateway,sentinel,java

    成功完成路由級(jí)別的限流,那么后面看看API維度的限流

自定義API維度

? 上面那種限流方式可以看出靈活性不夠高。自定義的API維度可以利用Sentinel提供的API自定義分組來進(jìn)行限流。相比路由維度,這是一種更加細(xì)粒度的限流方式。

實(shí)現(xiàn)

  1. 導(dǎo)入Gateway的適配包

    <!--sentinel為gateway提供的適配包-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    </dependency>
    
  2. 依然是實(shí)例化SentinelGatewayFilterSentinelBlockExceptionHandler對(duì)象,初始化限流規(guī)則,定義API分組

    @Configuration  // 配置類
    public class SentinelRouteConfiguration {   // 路由限流規(guī)則配置類
    
        private final List<ViewResolver> viewResolvers;
    
        private final ServerCodecConfigurer serverCodecConfigurer;
    
    
        public SentinelRouteConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @PostConstruct
        public void initGatewayRules() {    // 初始化限流規(guī)則
            Set<GatewayFlowRule> rules = new HashSet<>();
            GatewayFlowRule gatewayFlowRule = new GatewayFlowRule("user_api");    // 資源名,api分組的名稱(自定義)
            gatewayFlowRule.setCount(1);    // 限流閾值
            gatewayFlowRule.setIntervalSec(1);  // 統(tǒng)計(jì)時(shí)間窗口,默認(rèn)1s
    
            rules.add(gatewayFlowRule);
            GatewayRuleManager.loadRules(rules);    // 載入規(guī)則
        }
    
        @PostConstruct
        public void initCustomizedApis() {
            Set<ApiDefinition> apiDefinitions = new HashSet<>();
            ApiDefinition apiDefinition = new ApiDefinition("user_api") // 定義 api分組
                    .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                            add(new ApiPathPredicateItem()
                                    .setPattern("/user/group/**")	// 路徑匹配規(guī)則
                                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)); // 匹配策略,前綴匹配
                        }});
            apiDefinitions.add(apiDefinition);
    
            GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions); // 載入API分組定義
    
        }
    
        @PostConstruct
        public void initBlockHandlers() {    // 限流后的響應(yīng)
            BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
                Map<String, Object> result = new HashMap<>();
                result.put("code", "0");
                result.put("message", "您已被限流");
                return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(result));
            };
    
            GatewayCallbackManager.setBlockHandler(blockRequestHandler);    // 設(shè)置限流響應(yīng)
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
            return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter sentinelGatewayFilter() {   // 初始化限流過濾器
            return new SentinelGatewayFilter();
        }
    
    }
    

    唯一要注意的是:路由匹配規(guī)則如果是單一的一個(gè)具體接口,不是匹配符,那么后面的匹配策略就沒有必要再去配置了(setMatchStrategy()方法)

  3. 定義一個(gè)/user/group/findById接口

    @RequestMapping("/user/group/findById")
    public String findGById(@RequestParam("id") Integer id) {
        return userInfo.getOrDefault(id, null);
    }
    
  4. 啟動(dòng)調(diào)用測(cè)試

    SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由維度、API維度進(jìn)行流控,SpringCloud,SpringBoot,Java,gateway,sentinel,java

    可以看到配置的沒有問題,滿足/user/group/**規(guī)則的請(qǐng)求,有被限流到

超時(shí)配置

Gateway默認(rèn)沒有超時(shí)的限制,也就是數(shù)據(jù)什么時(shí)候返回,就等待到什么時(shí)候。如果不想等待,可以增加對(duì)超時(shí)的配置

gateway:
  httpclient:
    connect-timeout: 5000 # 建立連接時(shí)間限制,單位毫秒
    response-timeout: 4s  # 響應(yīng)時(shí)間的時(shí)間限制

嘗試下,接口睡眠5s,再次調(diào)用

curl localhost:8083/user/group/findById?id=1
{"timestamp":"2023-09-02T00:59:47.184+00:00","path":"/user/group/findById","status":504,"error":"Gateway Timeout","requestId":"7f5ff558-1"}

被告知504,超時(shí)了~

CORS配置

涉及到前后端分離的跨域請(qǐng)求時(shí),瀏覽器訪問后端地址通常提示No Access-Control-Allow-Origin header is present on the requested resource

可以在gateway中增加跨域配置,或者前端去配置都可以,自行協(xié)商。

cloud:
  nacos:
    discovery:
      server-addr: localhost:8848 # nacos地址
  gateway:
    httpclient:
      connect-timeout: 5000 # 建立連接時(shí)間限制,單位毫秒
      response-timeout: 4s  # 響應(yīng)時(shí)間的時(shí)間限制
    globalcors:
      cors-configurations: 
        '[/**]':
          allowedOrigins: "*" # 允許的來源
          allowedMethods: "*" # 允許的方法
          allowedHeaders: "*" # 允許的請(qǐng)求頭  *表示所有

通常情況下,也可以不是按照全部允許來做,按照你的項(xiàng)目實(shí)際開發(fā)需求搞就行了。文章來源地址http://www.zghlxwxcb.cn/news/detail-691629.html

到了這里,關(guān)于SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由維度、API維度進(jìn)行流控的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Cloud 之 Sentinel簡(jiǎn)介與GATEWAY整合實(shí)現(xiàn)

    Spring Cloud 之 Sentinel簡(jiǎn)介與GATEWAY整合實(shí)現(xiàn)

    隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來越重要。Sentinel 是面向分布式服務(wù)架構(gòu)的流量控制組件,主要以流量為切入點(diǎn),從限流、流量整形、熔斷降級(jí)、系統(tǒng)負(fù)載保護(hù)、熱點(diǎn)防護(hù)等多個(gè)維度來幫助開發(fā)者保障微服務(wù)的穩(wěn)定性。 熔斷 微服務(wù)架構(gòu)的系統(tǒng)通常會(huì)包含

    2024年02月19日
    瀏覽(21)
  • SpringCloud之Gateway整合Sentinel服務(wù)降級(jí)和限流

    SpringCloud之Gateway整合Sentinel服務(wù)降級(jí)和限流

    1.下載Sentinel.jar可以圖形界面配置限流和降級(jí)規(guī)則 地址:可能需要翻墻 下載jar文件 2.引入maven依賴 3.寫個(gè)自動(dòng)注入Resource的過濾器類(可以不寫注解直接使用) 4.寫配置文件 application.properties 5.cmd命令行啟動(dòng)jar文件訪問localhost:18080頁面,自己設(shè)置QPS java -jar -server.port=18080 sentinel-dash

    2024年02月07日
    瀏覽(23)
  • Spring Cloud Gateway 整合 sentinel 實(shí)現(xiàn)流控熔斷

    Spring Cloud Gateway 整合 sentinel 實(shí)現(xiàn)流控熔斷

    ????????在微服務(wù)架構(gòu)中,網(wǎng)關(guān)層可以屏蔽外部服務(wù)直接對(duì)內(nèi)部服務(wù)進(jìn)行調(diào)用,對(duì)內(nèi)部服務(wù)起到隔離保護(hù)的作用,網(wǎng)關(guān)限流,顧名思義,就是通過網(wǎng)關(guān)層對(duì)服務(wù)進(jìn)行限流,從而達(dá)到保護(hù)后端服務(wù)的作用。 ????????Sentinel 從 1.6.0 版本開始就提供了 Spring Cloud Gateway 的適配

    2023年04月23日
    瀏覽(23)
  • 【SpringCloudAlibaba】Sentinel使用

    【SpringCloudAlibaba】Sentinel使用

    https://github.com/alibaba/Sentinel 中文: https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D https://sentinelguard.io/zh-cn/docs/introduction.html 服務(wù)雪崩 服務(wù)降級(jí) 服務(wù)熔斷 服務(wù)限流 https://github.com/alibaba/Sentinel/releases Sentinel采用的懶加載 直接(默認(rèn)) 資源名:默認(rèn)rest路徑名 來源:默認(rèn) 關(guān)聯(lián) 當(dāng)與

    2024年02月10日
    瀏覽(18)
  • SpringCloudAlibaba之Sentinel介紹

    SpringCloudAlibaba之Sentinel介紹

    Sentinel 是阿里開源的一款面向分布式、多語言異構(gòu)化服務(wù)架構(gòu)的流量治理組件。 主要以流量為切入點(diǎn),從流量路由、流量控制、流量整形、熔斷降級(jí)、系統(tǒng)自適應(yīng)過載保護(hù)、熱點(diǎn)流量防護(hù)等多個(gè)維度來幫助開發(fā)者保障微服務(wù)的穩(wěn)定性。 上面兩句話來自 Sentinel 官網(wǎng)的自我介紹

    2024年02月09日
    瀏覽(16)
  • springCloudAlibaba集成sentinel實(shí)戰(zhàn)(超詳細(xì))

    springCloudAlibaba集成sentinel實(shí)戰(zhàn)(超詳細(xì))

    Sentinel是阿里開源的項(xiàng)目,提供了流量控制、熔斷降級(jí)、系統(tǒng)負(fù)載保護(hù)等多個(gè)維度來保障服務(wù)之間的穩(wěn)定性。 分布式系統(tǒng)的流量防衛(wèi)兵: 隨著微服務(wù)的普及,服務(wù)調(diào)用的穩(wěn)定性變得越來越重要。Sentinel以“流量”為切入點(diǎn),在流量控制、斷路、負(fù)載保護(hù)等多個(gè)領(lǐng)域開展工作,

    2024年04月15日
    瀏覽(35)
  • SpringCloudAlibaba之Sentinel(一)流控篇

    SpringCloudAlibaba之Sentinel(一)流控篇

    為什么使用Sentinel,這是一個(gè)高可用組件,為了使我們的微服務(wù)高可用而生 我們的服務(wù)會(huì)因?yàn)槭裁幢淮蚩澹?一,流量激增? ? 緩存未預(yù)熱,線程池被占滿 ,無法響應(yīng) 二,被其他服務(wù)拖垮,比如第三方的接口響應(yīng)慢 三,異常沒有處理:緩存擊穿,緩存穿透等等 總之而言:系

    2024年02月14日
    瀏覽(23)
  • 4.springcloudalibaba sentinel v1.8.6版本服務(wù)搭建

    4.springcloudalibaba sentinel v1.8.6版本服務(wù)搭建

    前面完成了gateway項(xiàng)目部署并且測(cè)試,現(xiàn)在部署搭建sentinel服務(wù)并且測(cè)試。 下載地址 這里選擇的是目前最新的sentinel版本 直接下載啟動(dòng)jar包,使用命令安裝服務(wù) 使用設(shè)置的賬號(hào)密碼登錄如下圖所示啟動(dòng)成功 完整pom如下 完整的配置如下 啟動(dòng)服務(wù)后,查看控制臺(tái),發(fā)現(xiàn)server服務(wù)

    2024年02月07日
    瀏覽(12)
  • 基于SpringCloudAlibaba+Sentinel的分布式限流設(shè)計(jì)

    胡弦,視頻號(hào)2023年度優(yōu)秀創(chuàng)作者,互聯(lián)網(wǎng)大廠P8技術(shù)專家,Spring Cloud Alibaba微服務(wù)架構(gòu)實(shí)戰(zhàn)派(上下冊(cè))和RocketMQ消息中間件實(shí)戰(zhàn)派(上下冊(cè))的作者,資深架構(gòu)師,技術(shù)負(fù)責(zé)人,極客時(shí)間訓(xùn)練營(yíng)講師,四維口袋KVP最具價(jià)值技術(shù)專家,技術(shù)領(lǐng)域?qū)<覉F(tuán)成員,2021電子工業(yè)出版社年度優(yōu)

    2024年04月22日
    瀏覽(23)
  • 重寫RuoYi-Cloud所有功能 整合 SpringCloudAlibaba Dubbo Mybatis-Plus MQ OSS ES Xxl-Job Docker 全方位升級(jí) 定期同步

    轉(zhuǎn)載于:https://blog.csdn.net/weixin_40461281/article/details/122837923 RuoYi-Cloud-Plus? 微服務(wù)通用權(quán)限管理系統(tǒng) ?重寫 RuoYi-Cloud 全方位升級(jí)(不兼容原框架) 系統(tǒng)演示:?傳送門?分布式集群版本(功能一致) 功能介紹 使用技術(shù) 文檔地址 特性注意事項(xiàng) 微服務(wù)權(quán)限管理系統(tǒng) RuoYi-Cloud-Plus RuoYi-Clo

    2024年02月08日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包