当前位置:网站首页>【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
【微服务|Sentinel】重写sentinel的接口BlockExceptionHandler
2022-07-02 22:01:00 【步尔斯特】
上文,我们使用sentinel整合feign,让其在feign客户端统一对异常进行处理,其原理是在一个服务调用另一个服务的时候,如果检测到异常为BlockExceptionHandler,就使用兜底方法进行处理。
源码
让我们看一看BlockExceptionHandler的源码:
public interface BlockExceptionHandler {
void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception;
}
哦,原来是一个接口。
实现
那我们来看看实现类都有哪些,就一个默认的,好吧。
public class DefaultBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
// Return 429 (Too Many Requests) by default.
response.setStatus(429);
PrintWriter out = response.getWriter();
out.print("Blocked by Sentinel (flow limiting)");
out.flush();
out.close();
}
}
重写
这个错误熟悉吧,如果我们想自定义限流返回格式并且需要返回的信息可以区分开各种限流异常,就需要我们重写BlockExceptionHandler接口,比如:
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.JSON;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/** * @author issavior */
@Component
public class MyUrlBlockHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
Map<String,Object> backMap=new HashMap<>(16);
if (e instanceof FlowException){
backMap.put("code",-1);
backMap.put("msg","限流-异常啦");
}else if (e instanceof DegradeException){
backMap.put("code",-2);
backMap.put("msg","降级-异常啦");
}else if (e instanceof ParamFlowException){
backMap.put("code",-3);
backMap.put("msg","热点-异常啦");
}else if (e instanceof SystemBlockException){
backMap.put("code",-4);
backMap.put("msg","系统规则-异常啦");
}else if (e instanceof AuthorityException){
backMap.put("code",-5);
backMap.put("msg","认证-异常啦");
}
// 设置返回json数据
httpServletResponse.setStatus(200);
httpServletResponse.setHeader("content-Type","application/json;charset=UTF-8");
httpServletResponse.getWriter().write(JSON.toJSONString(backMap));
}
}
问题及解决
但是经过测试,发现,热点限流不太好用,那就用全局异常来拦截一下吧,哈哈哈,如果有知道原因或者有更好的办法,记得留言哦~
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/** * @author issavior */
@RestControllerAdvice
public class MyParamFlowException {
@ExceptionHandler(ParamFlowException.class)
public void test(HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setStatus(400);
PrintWriter out = response.getWriter();
out.print("触发热点限流限流");
out.flush();
out.close();
}
}
边栏推荐
- A specially designed loss is used to deal with data sets with unbalanced categories
- [shutter] shutter application life cycle (foreground state resumed | background state paused | inactive | component separation state detached)
- Tencent three sides: in the process of writing files, the process crashes, and will the file data be lost?
- Meibeer company is called "Manhattan Project", and its product name is related to the atomic bomb, which has caused dissatisfaction among Japanese netizens
- [shutter] shutter resource file use (import resource pictures | use image resources)
- [C question set] of V
- Oriental Aesthetics and software design
- 【剑指 Offer】57. 和为s的两个数字
- GEE:(二)对影像进行重采样
- *C language final course design * -- address book management system (complete project + source code + detailed notes)
猜你喜欢
![[shutter] shutter layout component (wrap component | expanded component)](/img/a7/824a990235fc5ce67841ebdcf001fb.jpg)
[shutter] shutter layout component (wrap component | expanded component)

What "real skills" should a million year old cloud native developer master? Alibaba, Tencent, meituan and byte decrypt together

Basic concepts of image and deep understanding of yuv/rgb

C语言,实现三子棋小游戏
![[shutter] shutter application theme (themedata | dynamic modification theme)](/img/77/6b0082368943aee7108ac550141f28.gif)
[shutter] shutter application theme (themedata | dynamic modification theme)

腾讯三面:进程写文件过程中,进程崩溃了,文件数据会丢吗?

The difference between include < > and include ""

How to write a good program when a big book speaks every day?
![[shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)](/img/f7/cb41d159e5c5ef3f4f1b9468d52ccc.jpg)
[shutter] shutter opens a third-party application (url|launcher plug-in search and installation | url| launcher plug-in official example | open browser | open a third-party application)

tinymce可视化编辑器增加百度地图插件
随机推荐
[shutter] shutter custom fonts (download TTF fonts | pubspec.yaml configure font resources | synchronize resources | globally apply fonts | locally apply fonts)
Technical solution of vision and manipulator calibration system
地理探测器原理介绍
Unity3d learning notes 4 - create mesh advanced interface
Web侧防御指南
Market Research - current situation and future development trend of cell-based seafood market
[shutter] shutter page life cycle (initialization period | createstate | initstate | update period | build | destroy period | dispose)
LightGBM原理及天文数据中的应用
[Jianzhi offer] 57 And are two numbers of S
B.Odd Swap Sort(Codeforces Round #771 (Div. 2))
Blue Bridge Cup Winter vacation homework (DFS backtracking + pruning)
VictoriaMetrics 简介
How do I access the kubernetes API?
Gee: (II) resampling the image
CVPR论文解读 | 弱监督的高保真服饰模特生成
Market Research - current market situation and future development trend of high tibial osteotomy plate
Evolution of messaging and streaming systems under the native tide of open source cloud
记录一下微信、QQ、微博分享web网页功能
【leetcode】1380. Lucky number in matrix
About test cases