Add maven dependency to the gateway project
<!-- 引入 sentinel跟网管层的整合 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
Add configuration information in application.yml
#配置sentinel
spring:
sentinel:
transport:
dashboard: localhost:8883
#控制台的port
port: 8719
Open the gateway menu bar on the sentinel page, add the flow control rule
API name is the serverId configured in the configuration file,
and then we customize the exception that is triggered if the traffic is too large, if the traffic is too large, the following information will be triggered to the front-end page
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.hjh.common.exception.BizCodeEnume;
import com.hjh.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
/**
* @date 2021-02-22 2:19 下午
* @description sentinel网关层 返回我们自己的东西错误代码
* TODO 响应式编程 - 天然支持大并发系统
*/
@Configuration
public class MySeckillSentinelConfig {
public MySeckillSentinelConfig() {
GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
/**
* 网关限流了请求,就会掉用此方法 Mono Flux
*/
@Override
public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
R error = R.error(BizCodeEnume.TO_MANY_REQUEST.getCode(), BizCodeEnume.TO_MANY_REQUEST.getMsg());
String s = JSON.toJSONString(error);
Mono<ServerResponse> body = ServerResponse.ok().body(Mono.just(s), String.class);
return body;
}
});
}
}
Normal data when the request is returned under normal circumstances The data
returned by the request is too large