1.在gateway服务模块中添加gateway整合sentinel的依赖
com.alibaba.cloud spring-cloud-alibaba-sentinel-gatewaycom.alibaba.cloud spring-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;
@Configuration
public class GatewayConfig {
@PostConstruct
public void init() {
initCustomizedApis();
initBlockHandler();
}
private void initCustomizedApis() {
Set definitions = new HashSet<>();
ApiDefinition api = new ApiDefinition("user-center")
.setPredicateItems(new HashSet() {{
add(new ApiPathPredicateItem().setPattern("/user-center
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);
}
}



