Selaa lähdekoodia

feat:测试Sentinel的@SentinelResource注解中fallbackClass的配置和fallbackClass的配置

yang yi 1 vuosi sitten
vanhempi
sitoutus
e403c34e4d

+ 26 - 0
member-service-provider_10000/src/main/java/anyi/space/memberServer/components/MySentinelFallbackHandler.java

@@ -0,0 +1,26 @@
+package anyi.space.memberServer.components;
+
+/**
+ * @ProjectName: distributedSystemLearn
+ * @FileName: MySentinelFallbackHandler
+ * @Author: 杨逸
+ * @Data:2025/9/19 16:21
+ * @Description: 自定义Sentinel的全局业务异常处理类
+ */
+public class MySentinelFallbackHandler {
+    /**
+     * 自定义业务异常处理方法
+     * 必须是静态方法
+     * @param e
+     * @return {@code String }
+     * @description:
+     * @author: 杨逸
+     * @data:2025/09/19 16:23:50
+     * @since 1.0.0
+     */
+    public static String myFallbackHandler(Throwable e){
+        String msg = "出现业务异常=" + e.getMessage();
+        System.out.println(msg);
+        return msg;
+    }
+}

+ 36 - 0
member-service-provider_10000/src/main/java/anyi/space/memberServer/controller/SentinelTestController.java

@@ -1,6 +1,7 @@
 package anyi.space.memberServer.controller;
 
 import anyi.space.memberServer.components.MySentinelBlockHandler;
+import anyi.space.memberServer.components.MySentinelFallbackHandler;
 import com.alibaba.csp.sentinel.annotation.SentinelResource;
 import com.alibaba.csp.sentinel.slots.block.BlockException;
 import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
@@ -83,6 +84,17 @@ public class SentinelTestController {
         return msg;
     }
 
+    /**
+     * 使用全局阻塞处理方法处理
+     * 如果没有指定blockHandlerClass,则对应的blockHandler必须为当前类的public方法
+     * 指定了blockHandlerClass属性,则对应的blockHandler必须为对应类的静态方法
+     * blockHandler指定的方法参数和当前方法保持一致,除了最后一个参数,最后一个参数必须是BlockException类型
+     * @return {@code String }
+     * @description:
+     * @author: 杨逸
+     * @data:2025/09/19 16:19:22
+     * @since 1.0.0
+     */
     @SentinelResource(value = "t6",blockHandlerClass = MySentinelBlockHandler.class,blockHandler = "myBlockHandler")
     @GetMapping("/t6")
     public String t6(){
@@ -91,6 +103,30 @@ public class SentinelTestController {
         return msg;
     }
 
+    /**
+     * 业务异常处理类测试使用的接口
+     * 如果没有指定fallbackClass,则fallback必须为当前类的public方法
+     * 指定了fallbackClass,则fallback必须为对应类的public静态方法
+     * fallback指定的方法参数和当前方法保持一致,除了最后一个参数,最后一个参数必须是Throwable类型
+     * @return {@code String }
+     * @description:
+     * @author: 杨逸
+     * @data:2025/09/19 16:27:27
+     * @since 1.0.0
+     */
+    @SentinelResource(value = "t7",fallbackClass = MySentinelFallbackHandler.class,fallback = "myFallbackHandler",blockHandlerClass = MySentinelBlockHandler.class,blockHandler = "myBlockHandler")
+    @GetMapping("/t7")
+    public String t7(){
+        String msg = "t7被执行";
+        number++;
+        if (number % 5 == 0){
+            //模拟业务出现异常
+            int e = 1/0;
+        }
+        System.out.println(msg);
+        return msg;
+    }
+
     /**
      * news为测试Sentinel热点规则的接口
      * @param id