项目结构
父工程引入相关包
<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${alibaba.cloud-version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>版本号:
<alibaba.cloud-version>2.2.5.RELEASE</alibaba.cloud-version> <spring-cloud.version>Hoxton.SR8</spring-cloud.version> <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
子工程引入相关包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-core</artifactId> </dependency>
定义拦截规则
//定义规则 @PostConstruct public void initFlowRules(){ List<FlowRule> rules = new ArrayList<>(); FlowRule flowRule = new FlowRule(); flowRule.setResource("lanjie"); flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); flowRule.setCount(2); rules.add(flowRule); FlowRuleManager.loadRules(rules); }
控制器方法中实现限流
@RequestMapping("/home") public String home(){ try { SphU.entry("lanjie"); return "home"; } catch (BlockException e) { e.printStackTrace(); return "系统被限流"; } }
最后效果
访问地址:
http://localhost:8080/app/home 当前一秒超过2次访问就提示限流