大概原理:通过反射解析注解 @SentinelResource信息完成调用,处理方法,类似AOP编程
处理方法的返回类型要保持一致,参数和顺序保持一致, 可以在参数列表最后加
com.alibaba.csp.sentinel.slots.block.BlockException;
/**
* 如果不在同类,需要指明类名和方法名并且方法必须是静态方法
*/
@GetMapping("/add2")
@SentinelResource(value = "add", blockHandlerClass = {FlowContrlHandler.class}, blockHandler = "flow")
public String add2() {
System.out.println("下单成功!开始远程调用库存服务");
return stockServiceFeign.reduct();
}
/**
* 如果在同类,只需要指明方法名
*/
@GetMapping("/flow")
@SentinelResource(value = "flow", blockHandler = "flowControlHandler")
public String flow() {
return "正常访问";
}
public String flowControlHandler(BlockException e) {
return "Sentinel: 请求频繁!请稍后再试!";
}
package com.ldj.cloud.order.handler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
/**
* User: ldj
* Date: 2024/4/18
* Time: 23:51
* Description: No Description
*/
public class FlowContrlHandler {
public static String flow(BlockException e) {
return "Sentinel_Static: 请求频繁!请稍后再试!";
}
}