1.引入依赖
<!--sentinel-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<!--用于引入阿里巴巴 Sentinel 的注解切面(AspectJ)支持-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
</dependency>
2. 定义接口规则
2.1定义需要风控接口的规则
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 初始化限流配置
*/
@Component
public class SentinelRuleConfig implements InitializingBean {
//InitializingBean接口在初始化时自动调用afterPropertiesSet()等方法初始化bean
@Override
public void afterPropertiesSet() throws Exception {
//创建了一个FlowRule对象的列表rules,用于存放所有的流量控制规则。
List<FlowRule> rules = new ArrayList<>();
//定义了一个具体的流量控制规则createOrderRule
FlowRule createOrderRule = new FlowRule();
//规则监控的资源名为create_short-link
createOrderRule.setResource("create_short-link");
//过setGrade(RuleConstant.FLOW_GRADE_QPS)设置了限流策略为基于QPS(每秒查询率)的限流。
createOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
//设置了QPS的阈值为1,意味着该资源每秒最多只能被访问1次。
createOrderRule.setCount(1);
//放入sentine的规则中
rules.add(createOrderRule);
FlowRuleManager.loadRules(rules);
}
}
2.2handler
如果触发风控,设置降级策略。
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zdz.shortlink.project.common.convention.result.Result;
import com.zdz.shortlink.project.dto.req.ShortLinkCreateReqDTO;
import com.zdz.shortlink.project.dto.resp.ShortLinkCreateRespDTO;
/**
* 自定义流控策略
*/
public class CustomBlockHandler {
//处理名称为createShortLinkBlockHandlerMethod
public static Result<ShortLinkCreateRespDTO> createShortLinkBlockHandlerMethod(ShortLinkCreateReqDTO requestParam, BlockException exception) {
return new Result<ShortLinkCreateRespDTO>().setCode("B100000").setMessage("当前访问网站人数过多,请稍后再试...");
}
}
2.3在代码中引入 Sentinel 注解控制流控规则。
/**
* 创建短链接
*/
@SentinelResource(
//这个属性指定了资源名称。Sentinel会根据这个名称来识别和统计资源的调用情况,进行流量控制、熔断降级等操作。
value = "create_short-link",
//当调用该资源的方法因触发流量控制规则而被阻塞时,将会调用createShortLinkBlockHandlerMethod方法作为处理被阻塞请求的备选逻辑。
blockHandler = "createShortLinkBlockHandlerMethod",
//如果你希望将处理阻塞逻辑的方法放在另一个类中,可以使用blockHandlerClass属性指定该类,并且该类中需要包含一个与blockHandler属性值同名的方法。
blockHandlerClass = CustomBlockHandler.class
)
@PostMapping("/api/short-link/v1/create")
public Result<ShortLinkCreateRespDTO> createShortLink(@RequestBody ShortLinkCreateReqDTO requestParam) {
return Results.success(shortLinkService.createShortLink(requestParam));
}