Spring Cloud GateWay 集成 Sentinel 分布式流量控制框架-阿里云开发者社区

开发者社区> 开发与运维> 正文

Spring Cloud GateWay 集成 Sentinel 分布式流量控制框架

简介: 本文基于 spring.boot2.1.11.RELEASE, spring.cloud Greenwich.SR4, Spring Cloud Alibaba2.1.1.RELEASE, Sentinel 1.7.1

本文基于 Spring Boot2.1.11.RELEASE, Spring Cloud Greenwich.SR4, Spring Cloud Alibaba2.1.1.RELEASE, Sentinel 1.7.1

首先在网关模块 加入maven依赖, 等待maven 下载依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    <version>1.7.1</version>
</dependency>

image
作者这边没有指定版本号是因为做了统一的版本处理
然后编写 配置类

import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
* Gateway Sentinel 配置
* @author Jeckxu
*/
@Configuration
public class GatewayConfiguration {

   private final List<ViewResolver> viewResolvers;
   private final ServerCodecConfigurer serverCodecConfigurer;

   public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                               ServerCodecConfigurer serverCodecConfigurer) {
       this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
       this.serverCodecConfigurer = serverCodecConfigurer;
   }

   @Bean
   @Order(Ordered.HIGHEST_PRECEDENCE)
   public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
       // Register the block exception handler for Spring Cloud Gateway.
       return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
   }

   @Bean
   @Order(Ordered.HIGHEST_PRECEDENCE)
   public GlobalFilter sentinelGatewayFilter() {
       return new SentinelGatewayFilter();
   }
}

到此, GateWay 模块集成 Sentinel Code工作已经完成!

打开你的Sentinel 控制台, 你会发现相关的接口记录已经在Web中展示
image

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章