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

本文基于 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>

Spring Cloud GateWay 集成 Sentinel 分布式流量控制框架
作者这边没有指定版本号是因为做了统一的版本处理
然后编写 配置类

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中展示
Spring Cloud GateWay 集成 Sentinel 分布式流量控制框架

上一篇:首届不宕机春晚背后:国服第一程序员C位出道


下一篇:RDS for MySQL 空间问题的原因和解决