个人随笔
目录
九、springCloudAlibaba-sentinel控制台的使用(直接流控)和统一异常处理
2023-11-01 21:25:23

我们在八、springCloudAlibaba-整合sentinel整合了sentinel,这里尝试直接用控制台试用下,并且进行自定义异常。

1、流量控制

从簇点链路中新增流量控制规则

可以看到,配置很简单,我们并没有对我们的业务代码进行影响,配置好后,我们尝试快速点击,发现会返回

  1. Blocked by Sentinel (flow limiting)

那这怎么办呢?我们怎么返回自定义的异常呢?

2、自定义异常

这里有两种方式,一种是用我们之前的每个业务请求都自定义对应的异常,也就是用@SentinelResource注解,比如这次我们加上

  1. @RequestMapping("/add")
  2. @SentinelResource(value = "add", blockHandler = "exceptionHandler")
  3. public String add(String id){
  4. return "新增订单成功"+id;
  5. }
  6. //自定义返回
  7. public String exceptionHandler(String id, BlockException ex) {
  8. // Do some log here.
  9. ex.printStackTrace();
  10. return "被限流了"+id;
  11. }

启动后,访问一下请求簇点链路就会有add这个资源名,然后我们再新增流控,发现返回了自定义异常。(注:这里的资源名不能再是/order/add ,不然不会生效的,具体原因后续如果看源码再分析)

上面这种加用注解的方式对我们的代码其实是有侵入的,所以我们可以自定义异常,也很简单,加上下面一个异常类即可,该异常类实现BlockExceptionHandler

  1. package com.suibibk.springCloud.order;
  2. import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
  3. import com.alibaba.csp.sentinel.slots.block.BlockException;
  4. import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
  5. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
  6. import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
  7. import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
  8. import com.alibaba.fastjson.JSON;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.http.MediaType;
  12. import org.springframework.stereotype.Component;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.IOException;
  16. import java.io.PrintWriter;
  17. @Component
  18. public class MyBlockExceptionHandler implements BlockExceptionHandler {
  19. Logger log = LoggerFactory.getLogger(this.getClass());
  20. public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
  21. //getRule返回资源、规则的详细信息
  22. log.info("BlockExceptionHandler BlockException================"+e.getRule());
  23. Result r = null;
  24. if(e instanceof FlowException){
  25. r = Result.error(100,"接口被限流了");
  26. }else if (e instanceof DegradeException){
  27. r = Result.error(101,"服务降级了");
  28. }else if (e instanceof ParamFlowException){
  29. r = Result.error(102,"热点参数限流了");
  30. }else if (e instanceof AuthorityException){
  31. r = Result.error(104,"授权规则不通过");
  32. }
  33. //返回Json数据
  34. httpServletResponse.setStatus(500);
  35. httpServletResponse.setCharacterEncoding("UTF-8");
  36. httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
  37. PrintWriter writer=null;
  38. try {
  39. writer=httpServletResponse.getWriter();
  40. writer.write(JSON.toJSONString(r));
  41. writer.flush();
  42. } catch (IOException ioException) {
  43. log.error("异常:{}",ioException);
  44. }finally {
  45. if(writer!=null) {
  46. writer.close();
  47. }
  48. }
  49. }
  50. }

统一返回封装

  1. package com.suibibk.springCloud.order;
  2. public class Result<T> {
  3. private Integer code;
  4. private String msg;
  5. private T data;
  6. public Result(Integer code, String msg, T data) {
  7. this.code = code;
  8. this.msg = msg;
  9. this.data = data;
  10. }
  11. public Result(Integer code, String msg) {
  12. this.code = code;
  13. this.msg = msg;
  14. }
  15. public Integer getCode() {
  16. return code;
  17. }
  18. public void setCode(Integer code) {
  19. this.code = code;
  20. }
  21. public String getMsg() {
  22. return msg;
  23. }
  24. public void setMsg(String msg) {
  25. this.msg = msg;
  26. }
  27. public T getData() {
  28. return data;
  29. }
  30. public void setData(T data) {
  31. this.data = data;
  32. }
  33. public static Result error(Integer code,String msg){
  34. return new Result(code,msg);
  35. }
  36. }

然后就不用加@SentinelResource注解了,继续控制台新建流控,此时再测试就会返回自定义的反悔了

  1. {
  2. "code": 100,
  3. "msg": "接口被限流了"
  4. }

这里推荐用这种方式,对业务逻辑代码侵入较小
后台也打印出了异常的详细信息

  1. 2023-11-01 21:20:16.840 INFO 17948 --- [nio-8089-exec-2] c.s.s.order.MyBlockExceptionHandler : BlockExceptionHandler BlockException================FlowRule{resource=/order/add, limitApp=default, grade=1, count=2.0, strategy=0, refResource=null, controlBehavior=0, warmUpPeriodSec=10, maxQueueingTimeMs=500, clusterMode=false, clusterConfig=ClusterFlowConfig{flowId=null, thresholdType=0, fallbackToLocalWhenFail=true, strategy=0, sampleCount=10, windowIntervalMs=1000, resourceTimeout=2000, resourceTimeoutStrategy=0, acquireRefuseStrategy=0, clientOfflineTime=2000}, controller=com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController@39a550ee}

我们可以根据这些信息进行更加个性化的异常定制。如果需要更加特殊对某个请求进行专门定制的话,可以用回上面注解的模式!

 64

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2