Springboot使用Sentinel,还是稍显复杂。alibaba封装了针对Springcloud的使用,更加简单。
还是上次启动的那个控制台。
一、创建Springboot工程
二、添加Pom依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2021.1</version>
</dependency>
三、修改yml配置文件
server:
port: 8080
spring:
application:
name: springcloud-sentinel-demo-20210531
cloud:
sentinel:
transport:
dashboard: localhost:8756
在Springboot的整合中需要在JVM添加参数,Springcloud只需要在yml添加配置即可。
四、创建限流处理类
package com.chris.sentinel;
import com.alibaba.csp.sentinel.slots.block.BlockException;
/**
* @author Chris Chan
* Create on 2021/5/31 14:54
* Use for:
* Explain: 限流处理器
*/
public class TestBlockHandlerManager {
public static String testBlockHandler(BlockException e) {
return "The system is busy. Please try again later.";
}
}
和上次是一样的。把限流处理方法跟接口放一起是不合适的,尤其是当很多方法的处理方式都不一样的时候,最好还是用一个类专门管理起来。保证类的功能单一。
五、创建测试接口
package com.chris.sentinel;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Chris Chan
* Create on 2021/5/31 14:52
* Use for:
* Explain:
*/
@RestController
@RequestMapping("api/test")
public class TestController {
@SentinelResource(value = "test", blockHandlerClass = TestBlockHandlerManager.class, blockHandler = "testBlockHandler")
@GetMapping("test")
public String test() {
return "Called api/test/test success.";
}
}
六、启动程序
七、在控制台添加一个流控规则,设置每秒访问超过两次即被限流。
八、反复刷新调用test接口
当刷新缓慢时,返回正常。
当快速刷新时,返回系统繁忙。