SpringBoot整合SpringCloudAlibabaSentinel

一、介绍

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从流量控制、熔断降级、系统自适应保护等多个维度来帮助您保障微服务的稳定性。

2、与Hystrix、resilience4j对比
Hystrix具有以下功能:

  1. 线程池隔离/信号量隔离 Sentinel 不支持线程池隔离;信号量隔离对应 Sentinel 中的线程数限流。
  2. 熔断器 Sentinel 支持按平均响应时间、异常比率、异常数来进行熔断降级。
  3. Command 创建 直接使用 Sentinel SphU API 定义资源即可,资源定义与规则配置分离。
  4. 规则配置 在 Sentinel 中可通过 API 硬编码配置规则,也支持多种动态规则源
  5. 注解支持 Sentinel 也提供注解支持
  6. 开源框架支持 Sentinel 提供 Servlet、Dubbo、Spring Cloud、gRPC 的适配模块,开箱即用;若之前使用 Spring Cloud Netflix,可迁移至 Spring Cloud Alibaba

Hystrix官方已经停止更新

SpringBoot整合SpringCloudAlibabaSentinel_第1张图片二、Sentinel安装

安装环境及工具:CentOS7、docker

1、在docker仓库中查找Sentinel

docker search sentinel

SpringBoot整合SpringCloudAlibabaSentinel_第2张图片

2、从仓库中拉取其中一个版本,这里选取sentinel-dashboard最新版

docker pull bladex/sentinel-dashboard:latest

 3、查看docker镜像

docker images

 4、启动sentinel-dashboard

docker run -d -p 8558:8558 --name sentinel-dashboard aa398704ebd3

 5、查看docker容器,sentinel-dashboard已启用

docker ps

 6、浏览器访问该地址:服务器(宿主机)ip:8858,其中初始用户名和密码均为sentinel

SpringBoot整合SpringCloudAlibabaSentinel_第3张图片

 三、建立SpringBoot项目整合SpringCloudAlibabaSentinel

1、添加依赖

        
            com.alibaba.cloud
            spring-cloud-alibaba-sentinel
            2.1.0.RELEASE
        

2、配置参数

server:
  port: 8921

spring:
  cloud:
    sentinel:
      transport:
        dashboard: 192.168.91.133:8858

3、测试两个接口,其中/test接口是简单测试连接上sentinel-dashboard接口,/thread接口用于模拟高并发场景

(1)、通过/test接口简单测试

    @SentinelResource(value = "test")
    @GetMapping("/test")
    public String sentinel(){
        return "hello,welcome to sentinel's world!";
    }

访问localhost:8921/test

   成功访问并返回值

SpringBoot整合SpringCloudAlibabaSentinel_第4张图片 查看sentinel-dashboard,可见该项目已经通过配置文件成功被sentinel-dashboard实时监控

SpringBoot整合SpringCloudAlibabaSentinel_第5张图片

(2)、通过/thread接口用于模拟高并发场景

      controller:

    @GetMapping("/thread")
    public void multiThread(){
        for(int i=0;i<9000;i++){
            Thread thread= new Thread(multiThread);
            thread.start();
        }

    }

        service:

package com.example.springcloudalibabasentinel.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;

@Service
public class multiThread implements Runnable{
    Integer i=0;

    @SentinelResource(value = "run")
    @Override
    public void run() {
        try{
            System.out.println("开始计数"+(i++));
            Thread.sleep(2000);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

  访问localhost:8921/thread,查看sentinel-dashboard控制中台 

SpringBoot整合SpringCloudAlibabaSentinel_第6张图片

由于按访问线程数设置了流控规则,故出现了被拒绝QPS

SpringBoot整合SpringCloudAlibabaSentinel_第7张图片

后续关于Sentinel的更多使用将会随着项目的推进继续更新,欢迎大家留言讨论!

你可能感兴趣的:(springcloud,springboot,spring,cloud,微服务)