sentinel统一返回
来源:4-4 Spring Cloud Alibaba使用场景

锅锅_java
2021-08-09
sentinel统一返回实现BlockExceptionHandler接口,出现流控,没有进来。
代码如下:
package org.wlyg.ewm.gateway.config;
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.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@Slf4j
public class SentinelExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
JSONObject result = new JSONObject();
result.put("RESULT", "7000");
String msg = null;
if (ex instanceof FlowException) {
msg = "流控规则被触发";
} else if (ex instanceof DegradeException) {
msg = "降级规则被触发";
} else if (ex instanceof ParamFlowException) {
msg = "热点规则被触发";
} else if (ex instanceof SystemBlockException) {
msg = "系统规则被触发";
} else if (ex instanceof AuthorityException) {
msg = "授权规则被触发";
}
result.put("RESMSG", msg);
log.error("异常统一返回:{}",result.toJSONString());
// http状态码
response.setStatus(200);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type", "application/json;charset=utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(result.toJSONString());
}
}
1回答
-
大目
2021-08-13
可以帮忙提供下您的完整代码不?可以将代码发到github或者gitee哦,我来调试看看。
目测代码没啥问题。00
相似问题