java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Cloud Gateway服务网关限流

Spring Cloud Gateway服务网关限流问题及解决

作者:阿Q说代码

这篇文章主要介绍了Spring Cloud Gateway服务网关限流问题及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

网关是所有请求的公共入口,所以可以在网关进行限流,而且限流的方式也很多,我们本次采用前面学过的 Sentinel 组件来实现网关的限流。

Sentinel 支持对 SpringCloud Gateway、Zuul等主流网关进行限流。

从1.6.0版本开始,Sentinel提供了SpringCloud Gateway的适配模块,可以提供两种资源维度的限流:

route限流

导入依赖

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

编写配置类

基于Sentinel的Gateway限流是通过其提供的Filter来完成的,使用时只需注入对应的SentinelGatewayFilter实例以及SentinelGatewayBlockExceptionHandler实例即可。

@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 GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    //配置初始化的限流参数
    @PostConstruct
    public void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("shop-product")//资源名称,对应路由id
                        .setCount(1)//限流阀值
                        .setIntervalSec(1)//统计时间窗口,单位是秒,默认是1秒
        );
        GatewayRuleManager.loadRules(rules);
    }


    //配置限流异常处理器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }

    //自定义限流异常页面
    @PostConstruct
    public void initBlockHandlers() {
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                Map map= new HashMap<>();
                map.put("code", 0);
                map.put("message", "接口被限流了");
                return ServerResponse
                        .status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON_UTF8)
                        .body(BodyInserters.fromObject(map));
            }
        } ;
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    }
}

其中,GatewayFlowRule 网关限流规则中提供了如下属性:

测试

在一秒钟内多次访问http://localhost:7000/product/product/1?token=1232就可以看到限流启作用了。

自定义API分组

自定义API分组是一种更细粒度的限流规则定义

//配置初始化的限流参数
@PostConstruct
public void initGatewayRules() {
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("shop_product_api").setCount(1).setIntervalSec(1));
    rules.add(new GatewayFlowRule("shop_order_api").setCount(1).setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);
}

//自定义API分组
@PostConstruct
private void initCustomizedApis(){
    Set<ApiDefinition> definitions = new HashSet<>();
    //定义小组1
    ApiDefinition api1 = new ApiDefinition("shop_product_api")
            .setPredicateItems(new HashSet<ApiPredicateItem>(){{
                //以/product/product/api1开头的请求
                add(new ApiPathPredicateItem().setPattern("/product/product/**")
                        .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
            }});
    //定义小组2
    ApiDefinition api2 = new ApiDefinition("shop_order_api")
            .setPredicateItems(new HashSet<ApiPredicateItem>(){{
                //完全匹配/order/order2/message
                add(new ApiPathPredicateItem().setPattern("/order/order2/message"));
            }});
    definitions.add(api1);
    definitions.add(api2);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}

在一秒钟内多次访问http://localhost:7000/product/product/1?token=1232也可以看到限流启作用了。

总结

到这儿,Gateway 服务网关限流的内容就已经介绍完了。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文