Merge pull request '【微服务流量控制】“Blocked by Sentinel (flow limiting)”提示更改' (#986) from otto/microservices:dev_monitoring into dev_monitoring

This commit is contained in:
otto 2025-08-21 16:36:29 +08:00
commit 0f0a639bf4
3 changed files with 54 additions and 0 deletions

View File

@ -34,6 +34,12 @@
<artifactId>microservices-common-redis</artifactId>
</dependency>
<!-- SpringCloud Alibaba Sentinel -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,47 @@
package com.microservices.common.security.handler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson2.JSONObject;
import com.microservices.common.core.domain.R;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request,
HttpServletResponse response,
BlockException ex) throws Exception {
R<?> body;
if (ex instanceof FlowException) { // 限流
body = R.fail(429, "请求过于频繁,请稍后重试");
} else if (ex instanceof DegradeException) { // 熔断
body = R.fail(500, "服务暂时不可用,请稍后重试");
} else if (ex instanceof ParamFlowException) { // 热点参数限流
body = R.fail(400, "热点参数限流");
} else if (ex instanceof AuthorityException) { // 授权规则
body = R.fail(403, "无权限访问该资源");
} else if (ex instanceof SystemBlockException) { // 系统规则
body = R.fail(500, "系统规则限制,无法访问");
} else { // 兜底
body = R.fail(500, "服务繁忙,请稍后重试");
}
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(JSONObject.toJSONString(body));
}
}

View File

@ -4,3 +4,4 @@ com.microservices.common.security.service.impl.RequestCustomServiceImpl
com.microservices.common.security.aspect.PreAuthorizeAspect
com.microservices.common.security.aspect.InnerAuthAspect
com.microservices.common.security.handler.GlobalExceptionHandler
com.microservices.common.security.handler.SentinelBlockExceptionHandler