0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例

  sentinel除了让服务提供方、消费方用之外,网关也能用它来限流。我们基于上次整的网关(参见0.9.0.RELEASE版本的spring cloud alibaba nacos+gateway网关实例)来看下怎么弄。只需动其中的两板斧:

  1、pom引入sentinel适配器:

        
            com.alibaba.csp
            sentinel-spring-cloud-gateway-adapter
            1.6.0
        

  2、新增一个配置类:

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
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.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 javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
public class GatewayConfiguration {

    private final List viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;

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

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

    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilter() {
        return new SentinelGatewayFilter();
    }

    @PostConstruct
    public void doInit() {
        initGatewayRules();
    }

    /**
     * 配置限流规则
     */
    private void initGatewayRules() {
        Set rules = new HashSet<>();
        rules.add(new GatewayFlowRule("lxytrans-consumer")
                .setCount(4) // 限流阈值
                .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒
        );
        rules.add(new GatewayFlowRule("lxytrans-provider")
                .setCount(3)
                .setIntervalSec(1)
        );
        GatewayRuleManager.loadRules(rules);
    }
}

  打完收功。把网关重新跑起来,我们依然基于之前的服务提供方和消费方测试,消费方并发5个限1个,提供方并发5个限2个:

0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例_第1张图片

0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例_第2张图片

 

你可能感兴趣的:(0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例)