springboot框架项目实践应用十三(springcloud alibaba整合sentinel)

1.引言

到这里,我们已经体验过了sentinel这个服务容错神奇的威力!其实在实际应用中,如果将sentinel整合到springcloud alibaba使用,会更加方便和强大。

考虑到可能有小伙伴还不熟悉spring cloud alibaba,我们先简单介绍一下,看到名字你应该已猜到了

  • springcloud alibaba,是阿里基于springcloud孵化的新一代微服务架构工具集
  • 如果你熟悉springcloud,简单理解起来,你同样熟悉springcloud alibaba,因为它们同祖同宗
  • springcloud alibaba在springcloud基础上,推出了一些新的组件,比如说nacos用于替换Eureka(Eureka官方已经不在维护了!),sentinel替换Hystrix(Hystrix官方已经不在维护了!)

因此,如果我们在做微服务架构技术栈选型的时候,不妨推荐小伙伴们选择springcloud alibaba,更详细的信息,请参考官网:spring.io/projects/sp...

同样顺便截个图:

2.整合springcloud alibaba sentinel

2.1.引入依赖管理

引入依赖管理,我们通常需要引入

  • springboot依赖管理
  • springcloud依赖管理
  • springcloud alibaba依赖管理

为什么需要引入这么多呢?因为springcloud基于springboot,springcloud alibaba基于springcloud,都引入以后,我们就可以在项目中放心使用spring全家桶组件了!

xml 复制代码
<!--公共变量定义-->
<properties>
    <java.version>1.8</java.version>
    <spring-boot.version>2.3.2.RELEASE</spring-boot.version>
    <spring-cloud.version>Hoxton.SR9</spring-cloud.version>
    <spring-cloud-alibaba.version>2.2.6.RELEASE</spring-cloud-alibaba.version>
 </properties>

<!--引入依赖管理-->
<dependencyManagement>
    <dependencies>
       <!--spring boot 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--spring cloud依赖管理-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!--spring cloud alibaba依赖管理-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2.2.引入sentinel依赖

引入spring-cloud-starter-alibaba-sentinel组件

xml 复制代码
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

引入sentinel starter组件依赖

从图上上,已经看到我们熟悉的sentinel通信模块、以及aop模块了。

2.3.初始化资源

初始化加载之前案例中的流控规则、熔断规则

MySentinelResource

java 复制代码
public interface MySentinelResource {
    /**
     * 流控资源
     */
    public static final String FLOW_RESOURCE = "flowResource";

    /**
     * 降级资源
     */
    public static final String DEGRADE_RESOURCE = "degradeResource";

}

LoadSentinelRules

java 复制代码
@Component
@Slf4j
public class LoadSentinelRules {

    public LoadSentinelRules(){
        // 初始化加载流控规则
        initFlowRules();
        log.info("加载了流控规则.");

        // 初始化加载熔断降级规则
        initDegradeRules();
        log.info("加载了熔断降级规则.");

    }


    /**
     * 初始化流控规则
     */
    public void initFlowRules(){
        // 流控规则集合
        List<FlowRule> flowRules = Lists.newArrayList();

        FlowRule rule = new FlowRule();
        rule.setResource(MySentinelResource.FLOW_RESOURCE);// 资源
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 流控阈值类型:qps
        rule.setCount(1);// 流控阈值:1

        flowRules.add(rule);

        FlowRuleManager.loadRules(flowRules);
    }

    /**
     * 初始化降级规则
     */
    public void initDegradeRules(){
        List<DegradeRule> degradeRules = Lists.newArrayList();

        DegradeRule rule = new DegradeRule();
        rule.setResource(MySentinelResource.DEGRADE_RESOURCE);// 资源
        rule.setGrade(RuleConstant.DEGRADE_GRADE_RT);// 阈值类型:慢调用比例
        rule.setMinRequestAmount(5);// 最小请求数
        rule.setTimeWindow(1);// 熔断时长,单位秒
        rule.setSlowRatioThreshold(1);// 比例阈值
        rule.setCount(1);// 最大RT 单位毫秒
        rule.setStatIntervalMs(1000);// 统计时长,单位毫秒

        degradeRules.add(rule);

        DegradeRuleManager.loadRules(degradeRules);

    }

}

2.4.编写应用

开发一个restful接口应用,并在接口方法上加上@SentinelResource注解。

java 复制代码
@RestController
@RequestMapping("sentinel")
@Slf4j
public class SentinelController {

    /**
     * 测试限流
     * @return
     */
    @RequestMapping("test")
    @SentinelResource(value = MySentinelResource.FLOW_RESOURCE, blockHandler = "testBlockHandler")
    public String test(){
        log.info("SentinelController---test......");

        return "test ok !";
    }

    /**
     * 限流后处理方法
     * @param e
     * @return
     */
    public String testBlockHandler(BlockException e){
        log.error("限流异常了:{}", e);
        return "error,限流了!";
    }
}

2.5.测试流控效果

启动应用,访问接口:http://127.0.0.1:8080/sentinel/test,疯狂刷新!

总结,通过案例发现在springcloud alibaba中,整合使用sentinel更加方便,只需要导入sentinel-starter组件,以及在资源方法上使用@SentinelResource注解,即完成流控实现资源保护了。

3.整合接入控制面板

3.1.启动sentinel控制面板

打开cmd窗口,执行命令

shell 复制代码
cd D:\sentinel
java -Dserver.port=8858 -Dcsp.sentinel.dashboard.server=localhost:8858 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

3.2.增加sentinel配置

在需要接入dashboard控制面板的应用中,增加sentinel dashboard相关参数配置

yaml 复制代码
spring:
  application:
    name: follow-me-springcloud-sentinel2
  mvc:
    view:
      prefix: /pages/
      suffix: .html
  cloud:
    #sentinel相关配置
    sentinel:
      transport:
        #配置与dashboard控制面板通信端口
        port: 8719
        #配置dashboard控制面板地址
        dashboard: 127.0.0.1:8858
      #开启饥饿加载,默认懒加载
      eager: true

启动应用,刷新控制面板,发现应用已经接入进来!方便,真是太方便了!

3.3.测试熔断效果

编写一个资源,配置熔断规则,试一下熔断效果吧!

访问:http://127.0.0.1:8080/sentinel/grade/1,疯狂刷新,在增加熔断规则前,是不会有任何熔断的

java 复制代码
/**
 * 测试熔断降级
 * @param userId
 * @return
 */
 @RequestMapping("grade/{userId}")
 public String testGrade(@PathVariable("userId") String userId){

    log.info("SentinelController---testGrade......用户Id:{}",userId);

    return "test grade ok!";
}

在簇点链路找到端点:/sentinel/grade/{userId},增加熔断规则配置

再次访问端点:http://127.0.0.1:8080/sentinel/grade/1,疯狂刷新!这次熔断了!

本文源码地址:gitee.com/yanghouhua/...

相关推荐
程序猿chen10 分钟前
JVM考古现场(二十五):逆熵者·时间晶体的永恒之战(进阶篇)
java·jvm·git·后端·程序人生·java-ee·改行学it
CopyLower18 分钟前
Spring Boot的优点:赋能现代Java开发的利器
java·linux·spring boot
细心的莽夫20 分钟前
Elasticsearch复习笔记
java·大数据·spring boot·笔记·后端·elasticsearch·docker
程序员阿鹏30 分钟前
实现SpringBoot底层机制【Tomcat启动分析+Spring容器初始化+Tomcat 如何关联 Spring容器】
java·spring boot·后端·spring·docker·tomcat·intellij-idea
Asthenia04121 小时前
HTTPS 握手过程与加密算法详解
后端
刘大猫261 小时前
Arthas sc(查看JVM已加载的类信息 )
人工智能·后端·算法
Asthenia04121 小时前
操作系统/进程线程/僵尸进程/IPC与PPC/进程大小/进程的内存组成/协程相关/Netty相关拷打
后端
Asthenia04122 小时前
深入解析 MySQL 执行更新语句、查询语句及 Redo Log 与 Binlog 一致性
后端
杨充3 小时前
10.接口而非实现编程
后端
工业互联网专业3 小时前
基于JavaWeb的花店销售系统设计与实现
java·vue.js·spring boot·毕业设计·源码·课程设计·花店销售系统