代碼配置Sentinel

配置說(shuō)明參考:https://blog.csdn.net/m0_46379371/article/details/114904351
使用的依賴包:

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2021.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
            <version>2021.1</version>
        </dependency>

需求:對(duì)不同的應(yīng)用進(jìn)行不一樣的限流策略,并且對(duì)特定接口進(jìn)行通用限流

實(shí)現(xiàn)方法:不同應(yīng)用發(fā)送的請(qǐng)求時(shí)揽碘,由于項(xiàng)目的攔截器在sentinel的攔截器之前求厕,我會(huì)攔截所有的請(qǐng)求技竟,在請(qǐng)求頭中設(shè)置key為L(zhǎng)imitRulesKey苛秕,value為應(yīng)用code的鍵值對(duì)粉寞。由于項(xiàng)目初始化后奈梳,會(huì)讀取配置配置在redis中的各個(gè)應(yīng)用的限流策略并加載到sentinel中,sentinel會(huì)對(duì)匹配中攔截規(guī)則(例如正則匹配矢门,前綴匹配等)的請(qǐng)求中獲取請(qǐng)求的LimitRulesKey鍵值對(duì),拿redis中的應(yīng)用的code與LimitRulesKey鍵值對(duì)中的value進(jìn)行比較灰蛙,相等就進(jìn)行此應(yīng)用code對(duì)應(yīng)的限流策略祟剔,不相等就進(jìn)行配置接口的通用限流。sentinel每30分鐘讀取一次redis的應(yīng)用限流策略摩梧,更新已配置的限流策略
sentinel的配置類

@Configuration
@Slf4j
public class SentinelConfiguration {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CommonAppLimit commonAppLimit;

    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 JsonSentinelGatewayBlockExceptionHandler jsonSentinelGatewayBlockExceptionHandler() {
        return new JsonSentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    }


    @Bean
    @Order(-1)
    public GlobalFilter sentinelGatewayFilterConfiguration() {
        return new SentinelTsfGatewayFilter();
    }

    @PostConstruct
    public void doInit() {
        initCustomizedApis();
        initGatewayRules();
        List<AppNode> appNodes = initPropertyFromRedis();
        if (appNodes.size() > 0) {
            initCustomizedApisFromRedis(appNodes);
            initGatewayRulesFromRedis(appNodes);
        }
    }

    private List<AppNode> initPropertyFromRedis() {
        List<AppNode> appNodes = new ArrayList<>();
        try {
            log.info("=========執(zhí)行initPropertyFromRedis方法=========");
            Set<String> keys = stringRedisTemplate.keys("sentinel*");
            if (Objects.isNull(keys)) {
                return appNodes;
            }
            for (String key : keys) {
                try {
                    String sentinelConfig = stringRedisTemplate.opsForValue().get(key);
                    if (StringUtils.isEmpty(sentinelConfig)) {
                        continue;
                    }
                    log.info("initPropertyFromRedis的sentinelConfig:" + sentinelConfig);
                    AppNode appNode = JSON.parseObject(sentinelConfig, AppNode.class);
                    appNodes.add(appNode);
                } catch (Exception e) {
                    log.error("sentinel配置反序列化失敗:", e);
                }
            }
        } catch (Exception e) {
            log.error("讀取redis錯(cuò)誤", e);
        }
        return appNodes;
    }


    private void initCustomizedApis() {
        if (Objects.isNull(commonAppLimit)) {
            return;
        }
        if (commonAppLimit.getOpen()) {
            Set<ApiDefinition> definitions = new HashSet<>();
            ApiDefinition api = new ApiDefinition(commonAppLimit.getFlowRule());
            HashSet<ApiPredicateItem> apiPredicateItems = new HashSet<>();
            if (commonAppLimit.getUrls() != null && commonAppLimit.getUrls().size() > 0) {
                for (String limitUrl : commonAppLimit.getUrls()) {
                    apiPredicateItems.add(new ApiPathPredicateItem().setPattern(limitUrl)
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT));
                }
            }
            if (commonAppLimit.getPreUrls() != null && commonAppLimit.getPreUrls().size() > 0) {
                for (String limitUrl : commonAppLimit.getPreUrls()) {
                    apiPredicateItems.add(new ApiPathPredicateItem().setPattern(limitUrl)
                            .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                }
            }
            api.setPredicateItems(apiPredicateItems);
            definitions.add(api);
            GatewayApiDefinitionManager.loadApiDefinitions(definitions);
        }
        log.info("initCustomizedApis方法的GatewayRuleManager:" + GatewayRuleManager.getRules().toString());
    }

    private void initGatewayRules() {
        if (Objects.isNull(commonAppLimit)) {
            return;
        }
        if (commonAppLimit.getOpen()) {
            Set<GatewayFlowRule> rules = new HashSet<>();
            rules.add(new GatewayFlowRule(commonAppLimit.getFlowRule())
                    .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
                    .setCount(commonAppLimit.getCount())
                    .setBurst(commonAppLimit.getBurst())
                    .setIntervalSec(commonAppLimit.getIntervalSec())
                    .setParamItem(new GatewayParamFlowItem()
                            .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
                            .setFieldName("LimitRulesKey"))
            );
            GatewayRuleManager.loadRules(rules);
        }
        log.info("initCustomizedApis方法的GatewayRuleManager:" + GatewayRuleManager.getRules().toString());
    }


    private void initCustomizedApisFromRedis(List<AppNode> appNodes) {
        Set<ApiDefinition> definitions = GatewayApiDefinitionManager.getApiDefinitions();
        if (Objects.nonNull(appNodes) && appNodes.size() > 0) {
            for (AppNode appNode : appNodes) {
                ApiDefinition api = new ApiDefinition(appNode.getFlowRule());
                if (Objects.nonNull(appNode.getUrls()) && appNode.getUrls().size() > 0) {
                    HashSet<ApiPredicateItem> apiPredicateItems = new HashSet<>();
                    for (String testUrl : appNode.getUrls()) {
                        apiPredicateItems.add(new ApiPathPredicateItem().setPattern(testUrl)
                                .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                    }
                    api.setPredicateItems(apiPredicateItems);
                }
                definitions.add(api);
            }
        }
        GatewayApiDefinitionManager.loadApiDefinitions(definitions);
        log.info("initCustomizedApisFromRedis方法的GatewayApiDefinitionManager:" + GatewayApiDefinitionManager.getApiDefinitions());
    }

    private void initGatewayRulesFromRedis(List<AppNode> appNodes) {
        Set<GatewayFlowRule> rules = GatewayRuleManager.getRules();
        if (Objects.nonNull(appNodes) && appNodes.size() > 0) {
            for (AppNode appNode : appNodes) {
                rules.add(new GatewayFlowRule(appNode.getFlowRule())
                        .setResourceMode(SentinelGatewayConstants.RESOURCE_MODE_CUSTOM_API_NAME)
                        .setCount(appNode.getCount())
                        .setBurst(appNode.getBurst())
                        .setIntervalSec(appNode.getIntervalSec())
                        .setParamItem(new GatewayParamFlowItem()
                                .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_HEADER)
                                .setFieldName("LimitRulesKey")
                                .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_EXACT)
                                .setPattern(appNode.getCode())
                        )
                );
            }
        }
        GatewayRuleManager.loadRules(rules);
        log.info("initGatewayRulesFromRedis方法的GatewayRuleManager:" + GatewayRuleManager.getRules().toString());
    }


    @Scheduled(fixedDelay = 30 * 60 * 1000, initialDelay = 30 * 60 * 1000)
    public void loadSentinelConfig() {
        log.info("=======執(zhí)行l(wèi)oadSentinelConfig方法=========");
        List<AppNode> appNodes = initPropertyFromRedis();
        if (appNodes.size() == 0) {
            return;
        }
        log.info("appNodes:" + appNodes);
        initCustomizedApisFromRedis(appNodes);
        initGatewayRulesFromRedis(appNodes);
    }
}

自定義的handle


@Slf4j
public class JsonSentinelGatewayBlockExceptionHandler  implements WebExceptionHandler {
    private List<ViewResolver> viewResolvers;
    private List<HttpMessageWriter<?>> messageWriters;

    private final Supplier<ServerResponse.Context> contextSupplier = () -> {
        return new ServerResponse.Context() {
            public List<HttpMessageWriter<?>> messageWriters() {
                return JsonSentinelGatewayBlockExceptionHandler.this.messageWriters;
            }

            public List<ViewResolver> viewResolvers() {
                return JsonSentinelGatewayBlockExceptionHandler.this.viewResolvers;
            }
        };
    };

    public JsonSentinelGatewayBlockExceptionHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolvers;
        this.messageWriters = serverCodecConfigurer.getWriters();
    }

    private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
        log.info("執(zhí)行JsonSentinelGatewayBlockExceptionHandler的writeResponse方法");
        ServerHttpResponse serverHttpResponse = exchange.getResponse();
        serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        JSONObject responseObj = new JSONObject();
        responseObj.put("code", 444);
        responseObj.put("message", "請(qǐng)求過(guò)于頻繁物延,請(qǐng)稍后重試");
        responseObj.put("data", null);
        byte[] datas = responseObj.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas);
        return serverHttpResponse.writeWith(Mono.just(buffer));
    }

    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        } else {
            return !BlockException.isBlockException(ex) ? Mono.error(ex) : this.handleBlockedRequest(exchange, ex).flatMap((response) -> {
                return this.writeResponse(response, exchange);
            });
        }
    }

    private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
        return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
    }

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市仅父,隨后出現(xiàn)的幾起案子叛薯,更是在濱河造成了極大的恐慌,老刑警劉巖笙纤,帶你破解...
    沈念sama閱讀 206,126評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件耗溜,死亡現(xiàn)場(chǎng)離奇詭異褪测,居然都是意外死亡惧辈,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門闷旧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)蓉冈,“玉大人城舞,你說(shuō)我怎么就攤上這事∧穑” “怎么了家夺?”我有些...
    開封第一講書人閱讀 152,445評(píng)論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)伐弹。 經(jīng)常有香客問(wèn)我拉馋,道長(zhǎng),這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,185評(píng)論 1 278
  • 正文 為了忘掉前任煌茴,我火速辦了婚禮随闺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蔓腐。我一直安慰自己矩乐,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,178評(píng)論 5 371
  • 文/花漫 我一把揭開白布回论。 她就那樣靜靜地躺著散罕,像睡著了一般。 火紅的嫁衣襯著肌膚如雪傀蓉。 梳的紋絲不亂的頭發(fā)上欧漱,一...
    開封第一講書人閱讀 48,970評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音葬燎,去河邊找鬼误甚。 笑死,一個(gè)胖子當(dāng)著我的面吹牛谱净,可吹牛的內(nèi)容都是我干的靶草。 我是一名探鬼主播,決...
    沈念sama閱讀 38,276評(píng)論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼岳遥,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了裕寨?” 一聲冷哼從身側(cè)響起浩蓉,我...
    開封第一講書人閱讀 36,927評(píng)論 0 259
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎宾袜,沒想到半個(gè)月后捻艳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,400評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡庆猫,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,883評(píng)論 2 323
  • 正文 我和宋清朗相戀三年认轨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片月培。...
    茶點(diǎn)故事閱讀 37,997評(píng)論 1 333
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡嘁字,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出杉畜,到底是詐尸還是另有隱情纪蜒,我是刑警寧澤,帶...
    沈念sama閱讀 33,646評(píng)論 4 322
  • 正文 年R本政府宣布此叠,位于F島的核電站纯续,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜猬错,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,213評(píng)論 3 307
  • 文/蒙蒙 一窗看、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧倦炒,春花似錦显沈、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至智玻,卻和暖如春遂唧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背吊奢。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評(píng)論 1 260
  • 我被黑心中介騙來(lái)泰國(guó)打工盖彭, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人页滚。 一個(gè)月前我還...
    沈念sama閱讀 45,423評(píng)論 2 352
  • 正文 我出身青樓召边,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親裹驰。 傳聞我的和親對(duì)象是個(gè)殘疾皇子隧熙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,722評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容