一、背景介绍
Sentinel整合Gateway在默认情况下,URL触发限流后会直接返回 {code: 429, message: “Blocked by Sentinel: ParamFlowException”},我们可以也可以自定义返回。
二、具体方案
方案一:代码
package com.cyun.gateway.config;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
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.HashMap;
/**
* 限流降级方式一
*
* @author He PanFu
* @date 2022-03-03 16:17:25
*/
@Configuration
public class GatewayConfig {
@PostConstruct
public void init() {
BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
HashMap<String, Object> map = new HashMap<>();
map.put("code", HttpStatus.TOO_MANY_REQUESTS.value());
map.put("msg", "请稍后再试...");
map.put("success", true);
//自定义异常处理
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(map));
};
GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
}
方案二:配置文件
spring:
application:
name: gateway-server
profiles:
active: dev
cloud:
sentinel:
transport:
port: 7201
dashboard: localhost:7003
# 限流降级方式二
scg:
fallback:
# 响应模式 response、redirect
mode: response
# 响应状态码
response-status: 444
# 响应信息
response-body: "{\"code\":\"429\",\"msg\":\"请求太多了\"}"
content-type: application/json
order: -100
redirect: /errorPage.html # 响应模式为 'redirect' 模式对应的重定向 URL