gateway整合sentinel实现服务流控熔断降级

1.在gateway服务模块中添加gateway整合sentinel的依赖


com.alibaba.cloudspring-cloud-alibaba-sentinel-gateway

com.alibaba.cloudspring-cloud-starter-alibaba-sentinel

2. 在application.yml配置文件中添加sentinel控制台的配置

sentinel:  #sentinel的配置transport:dashboard: localhost:8080  #配置sentinel dashboard地址port:  8719   #默认端口8719

3. 编写gateway配置类,自定义限流配置

package com.mc.tutor.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.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;import com.mc.tutor.common.ResponseResult;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;/*** @ClassName GatewayConfig* @Description 网关配置* @Author PotatoBoy* @Date 2021/11/9 21:00* @Version 1.0**/
@Configuration
public class GatewayConfig {/** @Author PotatoBoy* @Description //初始化限流配置* @Date 2021/11/19 15:10* @Param []* @return void**/@PostConstructpublic void init() {initCustomizedApis();initBlockHandler();}/** @Author PotatoBoy* @Description //自定义api分组* @Date 2021/11/19 15:12* @Param []* @return void**/private void initCustomizedApis() {Set definitions = new HashSet<>();ApiDefinition api = new ApiDefinition("user-center").setPredicateItems(new HashSet() {{add(new ApiPathPredicateItem().setPattern("/user-center/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));}});definitions.add(api);//加载自定义的限流分组GatewayApiDefinitionManager.loadApiDefinitions(definitions);}/** @Author PotatoBoy* @Description //自定义限流异常处理器* @Date 2021/11/19 15:09* @Param * @return **/private void initBlockHandler() {BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) ->ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS).contentType(MediaType.APPLICATION_JSON).body(BodyInserters.fromValue(ResponseResult.sendFailMsg("您的请求过于频繁,请稍后再试!")));// 加载自定义的限流异常处理器GatewayCallbackManager.setBlockHandler(blockRequestHandler);}
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部