Spring Boot集成sentinel快速入门Demo

1.什么是sentinel?

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。

Sentinel 基本概念

资源

资源是 Sentinel 的关键概念。它可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码。在接下来的文档中,我们都会用资源来描述代码块。 只要通过 Sentinel API 定义的代码,就是资源,能够被 Sentinel 保护起来。大部分情况下,可以使用方法签名,URL,甚至服务名称作为资源名来标示资源。

规则

围绕资源的实时状态设定的规则,可以包括流量控制规则、熔断降级规则以及系统保护规则。所有规则可以动态实时调整。

Sentinel 的使用可以分为两个部分:

  • 核心库(Java 客户端):不依赖任何框架/库,能够运行于 Java 8 及以上的版本的运行时环境,同时对 Dubbo / Spring Cloud 等框架也有较好的支持(见 主流框架适配)。
  • 控制台(Dashboard):Dashboard 主要负责管理推送规则、监控、管理机器信息等。

2.sentinel-dashboard搭建

下载地址

运行dashboard

复制代码
java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.6.jar

访问http://127.0.0.1:8080,默认用户名和密码都是 sentinel。

3.代码工程

实验目标

利用Sentinel实现接口流量控制

pom.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sentinel</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>1.8.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>1.8.6</version>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

controller

复制代码
package com.et.sentinel.controller;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.et.sentinel.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloWorldController {
    @Autowired
    TestService testService;
    @RequestMapping("/hello")
    public Map<String, Object> showHelloWorld()  {

        Map<String, Object> map = new HashMap<>();
        try {
            map.put("msg", testService.sayHello("harries"));
        }catch (Exception e){
            System.out.println("sayHello blocked!");
        }
        return map;
    }
}

service

使用资源(HelloWorld)

复制代码
package com.et.sentinel.service;

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

@Service
public class TestService {

    @SentinelResource(value = "HelloWorld",blockHandler = "sayHello block")
    public String sayHello(String name) {

        return "Hello, " + name;
    }
}

config

配置注解

复制代码
package com.et.sentinel.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
 
@Configuration
public class SentinelAspectConfig {
 
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(){
        return new SentinelResourceAspect();
    }

}

DemoApplication.java

定义一个"HelloWorld"资源

复制代码
package com.et.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);

      // 配置规则.
      initFlowRules();
      /*while (true) {
         // 1.5.0 版本开始可以直接利用 try-with-resources 特性
         try (Entry entry = SphU.entry("HelloWorld")) {
            // 被保护的逻辑
            Thread.sleep(300);
            System.out.println("hello world");
         } catch (BlockException | InterruptedException ex) {
            // 处理被流控的逻辑
            System.out.println("blocked!");
         }
      }*/

   }

   private static void initFlowRules(){
      List<FlowRule> rules = new ArrayList<>();
      FlowRule rule = new FlowRule();
      rule.setResource("HelloWorld");
      rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
      // Set limit QPS to 20.
      rule.setCount(2);
      rules.add(rule);
      FlowRuleManager.loadRules(rules);
   }

}

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

4.测试

打包Spring Boot应用

复制代码
mvn install

运行程序(配置在application.yaml文件里面配追不生效,这块可能有一些bug,只能在启动的时候加上这个参数)

复制代码
java -Dcsp.sentinel.dashboard.server=127.0.0.1:8080 -jar sentinel-1.0-SNAPSHOT.jar

多访问几次http://127.0.0.1:8088/hello,登陆sentinel-dashboad看结果

可以看到通过多少流量,拒绝多少流量

5.引用

相关推荐
纪莫4 分钟前
A公司一面:类加载的过程是怎么样的? 双亲委派的优点和缺点? 产生fullGC的情况有哪些? spring的动态代理有哪些?区别是什么? 如何排查CPU使用率过高?
java·java面试⑧股
风一样的树懒42 分钟前
死信队列:你在正确使用么?
后端
RoyLin44 分钟前
TypeScript设计模式:门面模式
前端·后端·typescript
JavaGuide1 小时前
JDK 25(长期支持版) 发布,新特性解读!
java·后端
用户3721574261351 小时前
Java 轻松批量替换 Word 文档文字内容
java
白鲸开源1 小时前
教你数分钟内创建并运行一个 DolphinScheduler Workflow!
java
weiwenhao1 小时前
关于 nature 编程语言
人工智能·后端·开源
薛定谔的算法1 小时前
phoneGPT:构建专业领域的检索增强型智能问答系统
前端·数据库·后端
RoyLin1 小时前
TypeScript设计模式:责任链模式
前端·后端·typescript
RoyLin2 小时前
TypeScript设计模式:装饰器模式
前端·后端·typescript