六.Sentinel 版本1.8.0的扩展说明

2021-03-26  本文已影响0人  G__yuan

错误页面优化的扩展

可以自己实现BlockExceptionHandler接口(在sentinel之前的一些老版本中用的是UrlBlockHandler比如1.6.X)

@Component
public class CustomUrlBlockHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String msg = "";
        if (e instanceof FlowException){
            msg = "被限流了";
        }else if (e instanceof DegradeException){
            msg = "被降级了";
        }else if (e instanceof ParamFlowException){
            msg = "热点参数限流";
        }else if (e instanceof SystemBlockException){
            msg = "系统规则(负载/...不满足规则)";
        }else if (e instanceof AuthorityException){
            msg = "授权规则不通过";
        }
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type","application/json");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(msg);
        writer.flush();
        writer.close();
    }
}

实现区分来源

实现RequestOriginParser接口

@Component
public class CustomRequestOriginParser implements RequestOriginParser {
    @Override
    public String parseOrigin(HttpServletRequest request) {
       //TODO 可以通过在header中放入来源,来过滤对那些来源的请求进行限流,降级等,如果没有指定来源,可以直接抛异常,或者不处理。
        return null;
    }
}

对Restful url的扩展

实现UrlCleaner接口

@Component
public class CustomUrlCleaner implements UrlCleaner {
    @Override
    public String clean(String originUrl) {
        System.out.println(originUrl);
        //TODO 对一类的url进行统一返回一个资源名称,这样在添加限流规则的时候,就不需要每一个url进行规则设定。
        return originUrl;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读