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.引用

相关推荐
茜茜西西CeCe6 分钟前
移动技术开发:简单计算器界面
java·gitee·安卓·android-studio·移动技术开发·原生安卓开发
bjzhang756 分钟前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
救救孩子把10 分钟前
Java基础之IO流
java·开发语言
flying jiang11 分钟前
Spring Boot 入门面试五道题
spring boot
小菜yh12 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
宇卿.18 分钟前
Java键盘输入语句
java·开发语言
浅念同学19 分钟前
算法.图论-并查集上
java·算法·图论
希冀12319 分钟前
【操作系统】1.2操作系统的发展与分类
后端
立志成为coding大牛的菜鸟.31 分钟前
力扣1143-最长公共子序列(Java详细题解)
java·算法·leetcode
鱼跃鹰飞32 分钟前
Leetcode面试经典150题-130.被围绕的区域
java·算法·leetcode·面试·职场和发展·深度优先