springCloud Alibaba教程-sentinel入门实践

1.服务中引入sentinel

1 在pom.xml文件中引入sentinel依赖:

<dependency>
    <groupId>com.alibaba.cloudgroupId>
    <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
dependency>

2 编写一个测试controller

@RestController
@Slf4j
public class OrderV3Controller {
    @SentinelResource(value = "message1")
    @GetMapping("/order/message1")
    public String message1() {
        return "message1";
    }
}

3 sentinel控制台安装

下载sentinel控制台jar包,下载地址https://github.com/alibaba/Sentinel/releases

sentinel.jar启动命令:

# 直接使用jar命令启动项目(控制台本身是一个SpringBoot项目)
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.5.jar &

浏览器访问地址: http://localhost:8080/#/login,默认登陆的账号与密码为sentinel/sentinel
springCloud Alibaba教程-sentinel入门实践_第1张图片

4 服务中加入sentinel控制台相关配置

spring:
 cloud:
   sentinel:
     transport:
        #跟控制台交流的端口,随意指定一个未使用的端口即可
        port: 9999
        # 指定控制台服务的地址
        dashboard: localhost:8080
      enabled: true

5 启动服务,访问一下前面编写的接口

在这里插入图片描述
然后刷新一下sentinel控制台:
springCloud Alibaba教程-sentinel入门实践_第2张图片
为该接口添加一个限流规则:springCloud Alibaba教程-sentinel入门实践_第3张图片
springCloud Alibaba教程-sentinel入门实践_第4张图片
然后通过终端频繁访问该接口,观察效果:
springCloud Alibaba教程-sentinel入门实践_第5张图片

2.sentinel规则持久化到nacos

启动nacos,并添加配置:springCloud Alibaba教程-sentinel入门实践_第6张图片

项目增加sentinel规则持久化到nacos的依赖:

 <dependency>
    <groupId>com.alibaba.cspgroupId>
    <artifactId>sentinel-datasource-nacosartifactId>
dependency>

然后服务项目配置文件中增加如下配置:

spring:
  cloud:
    sentinel:
      datasource:
        ds1:
          nacos:
            server-addr: 127.0.0.1
            data-id: cloud-order-service
            group-id: DEFAULT_GROUP
            data-type: json
            rule-type: flow
            namespace: dev

启动以后,观察sentiel发现已经读取到了nacos中配置的规则。目前sentinel控制台只能从nacos读取配置规则,如果要将sentinel控制台配置的规则推送到nacos配置中心的化需要修改一下sentinel源码

你可能感兴趣的:(spring,cloud,alibaba,sentinel,spring,cloud)