alibaba/Sentinel实现zuul网关限流

暂时只实现了zuul网关限流,熔断降级功能暂未实现

pom.xml:

<dependency>
	<groupId>com.alibaba.csp</groupId>
	<artifactId>sentinel-zuul-adapter</artifactId>
	<version>1.8.0</version>
</dependency>

zuul部分配置:

zuul:
  ignored-services: '*'
  sensitiveHeaders:
  routes:
    agr-serivce:
      path: /api-agr-serivce/**
      serviceId: api-agr-serivce

ZuulSentinelConfig:

package com.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.common.SentinelGatewayConstants;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayParamFlowItem;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackManager;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.netflix.zuul.ZuulFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * 网关限流配置
 *
 * Created by ${lyt} on 2021/1/7 17:09
 */
@Configuration
public class ZuulSentinelConfig {

    @Bean
    public ZuulFilter sentinelZuulPreFilter() {
        return new SentinelZuulPreFilter();
    }

    @Bean
    public ZuulFilter sentinelZuulPostFilter() {
        return new SentinelZuulPostFilter();
    }

    @Bean
    public ZuulFilter sentinelZuulErrorFilter() {
        return new SentinelZuulErrorFilter();
    }

    @PostConstruct
    public void doInit() {
        // 注册 FallbackProvider
        ZuulBlockFallbackManager.registerProvider(new MyBlockFallbackProvider());

        initCustomizedApis();
        initGatewayRules();
    }

    /**
     * 自定义API分组
     */
    private void initCustomizedApis() {
        Set<ApiDefinition> definitions = new HashSet<>();

        ApiDefinition api1 = new ApiDefinition("customized_landmark")
        .setPredicateItems(new HashSet<ApiPredicateItem>() {{
            add(new ApiPathPredicateItem()
                    .setPattern("/api-landmark/landmark/**")
                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
            /*add(new ApiPathPredicateItem()
                    .setPattern("/api-landmark/landmark/getMonth**")
                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));*/
        }});

        definitions.add(api1);
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    }

    /**
     * 配置网关限流规则
     */
    private void initGatewayRules() {
        Set<GatewayFlowRule> rules = new HashSet<>();

        rules.add(new GatewayFlowRule("customized_landmark")
                .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME) //针对自定义API分组
                .setCount(1) // 限流阈值
                .setIntervalSec(3) // 统计时间窗口,单位是秒,默认是 1 秒
                .setParamItem(new GatewayParamFlowItem()
                        .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_CLIENT_IP)
                )
        );

        rules.add(new GatewayFlowRule("agr-serivce")
                .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_ROUTE_ID) //针对API Gateway的route
                .setCount(1) // 限流阈值
                .setIntervalSec(3) // 统计时间窗口,单位是秒,默认是 1 秒
                .setBurst(3) // 应对突发请求时额外允许的请求数目
                .setParamItem(new GatewayParamFlowItem()
                        //从url中解析参数
                        .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setPattern("1").setFieldName("iPhoneX")
                        //模糊匹配参数
                        .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS)
                )
                /*.setParamItem(new GatewayParamFlowItem()
                        //从header中解析参数
                        .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER).setPattern("1").setFieldName("a")
                        //模糊匹配参数
                        .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_CONTAINS))*/
        );

        GatewayRuleManager.loadRules(rules);
    }
}

MyBlockFallbackProvider:

package com.cloud.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.BlockResponse;
import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackProvider;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.netflix.zuul.context.RequestContext;

/**
 * 网关限流自定义返回信息
 * Created by ${lyt} on 2021/1/7 17:09
 */
public class MyBlockFallbackProvider implements ZuulBlockFallbackProvider {
    @Override
    public String getRoute() {
        return null;
    }

    @Override
    public BlockResponse fallbackResponse(String s, Throwable throwable) {
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.getResponse().setContentType("application/json; charset=utf-8");

        if (throwable instanceof BlockException) {
            return new BlockResponse(429, "访问频繁!!!", s);
        } else {
            return new BlockResponse(500, "系统异常!!!", s);
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值