1.引入 Sentinel
com.alibaba.cloud spring-cloud-starter-alibaba-sentinel
2.下载sentinel,然后启动Sentinel控制台
https://github.com/alibaba/Sentinel/releases/download/v1.8.0/sentinel-dashboard-1.8.0.jar
3.启动控制台
java -Dserver.port=9999 -Dcsp.sentinel.dashboard.server=localhost:9999 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.0.jar 其中 -Dserver.port=9999 用于指定 Sentinel 控制台端口为 9999
从 Sentinel 1.6.0 起,Sentinel 控制台引入基本的登录功能,默认用户名和密码都是sentinel.
4.配置文件添加sentinel配置:
spring: cloud: sentinel: transport: port: 6789 dashboard: localhost:9999
5. 添加测试方法
@RestControllerpublic class TestController { @Autowired private TestService service; @GetMapping(value = "/hello/{name}") public String apiHello(@PathVariable String name) { return service.sayHello(name); }}
@Servicepublic class TestService { //@SentinelResource 注解用来标识资源是否被限流、降级。上述例子上该注解的属性 sayHello 表示资源名 @SentinelResource(value = "sayHello") public String sayHello(String name) { return "Hello, " + name; }}
6.然后启动项目,进行一个模拟限流的操作:
如下是正常访问:
![901a980f0fff96470d649a6a9998a56d.png](https://i-blog.csdnimg.cn/blog_migrate/687053075ee9e52fbf2bac455662c9dc.jpeg)
进行上面的流控设置,然后会生成一条流控规则
![7d52adf17a9276fdb48bbcbac8e1554c.png](https://i-blog.csdnimg.cn/blog_migrate/8e3b7798bbf1e0a82b2290d360a3d1cc.jpeg)
如此一个简单的流量控制就完成了,还是比较方便的。
![80d43033c7273af595637624dc73e71d.png](https://i-blog.csdnimg.cn/blog_migrate/1d224e8b742127da0d3f2e5f242b5413.jpeg)