此Demo在抛出异常的方式定义资源 这个Demo中修改,整体代码大同小异
【仅是入门用】springboot-sentinel最基本入门Demo-1,代码方式编写限流规则,并接入到sintinel控制台,抛出异常的方式定义资源-CSDN博客
改动如下
1 添加maven依赖,增加了一个依赖
<!-- sentinel核心依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<version>1.7.2</version>
</dependency>
<!-- sentinel注解方式定义资源 -->
<!-- add新增加 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-annotation-aspectj</artifactId>
<version>1.7.2</version>
</dependency>
<!-- 本应用接入到sentinel控制台的依赖 -->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.7.2</version>
</dependency>
2 创建AspectJ 配置类(新增加)
package cn.jiqistudy.boot_1test.Config;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SentinelAspectConfiguration {
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
}
3 新建Controller测试方法
package cn.jiqistudy.boot_1test.Control;
import cn.jiqistudy.boot_1test.pojo.Yonghu;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
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.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
@RestController
public class test_5 {
/**
* 注解方式定义资源
*
* @return
* @SentinelResource value 资源名称
* @SentinelResource blockHandler 调用被限流/降级/系统保护的时候调用的方法
*/
@SentinelResource(value = "ziyuan_1", blockHandler = "blockHandler_method_1")
@RequestMapping("getuser")
public Object fangfa_1() {
Yonghu user_1 = new Yonghu(1, "zhangshan_" + System.currentTimeMillis(), "男", 23, "湖南");
return user_1;
}
/**
* 原方法调用被限流/降级/系统保护的时候调用
*/
public String blockHandler_method_1(BlockException ex) {
ex.printStackTrace();
return "系统繁忙,请稍后!";
}
/*
定义限流规则
在构造函数执行之后执行
*/
@PostConstruct
public void initFlowRules() {
//一模一样
}
}