SpringMvc集成开源流量监控、限流、熔断降级、负载保护组件Sentinel | 京东云技术团队

news2024/10/6 7:12:35

前言:作者查阅了Sentinel官网、51CTO、CSDN、码农家园、博客园等很多技术文章都没有很准确的springmvc集成Sentinel的示例,因此整理了本文,主要介绍SpringMvc集成Sentinel

SpringMvc集成Sentinel

一、Sentinel 介绍

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

GitHub主页:https://github.com/alibaba/Sentinel

中文文档:https://sentinelguard.io/zh-cn/docs/introduction.html

控制台文档:https://sentinelguard.io/zh-cn/docs/dashboard.html

核心类解析:https://github.com/alibaba/Sentinel/wiki/Sentinel-核心类解析

Sentinel示例项目:https://github.com/alibaba/Sentinel/tree/master/sentinel-demo

https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example

二、Sentinel 基本概念

资源

资源是 Sentinel 的关键概念。它可以是 Java 应用程序中的任何内容,例如,由应用程序提供的服务,或由应用程序调用的其它应用提供的服务,甚至可以是一段代码。在接下来的文档中,我们都会用资源来描述代码块。

只要通过 Sentinel API 定义的代码,就是资源,能够被 Sentinel 保护起来。大部分情况下,可以使用方法签名,URL,甚至服务名称作为资源名来标示资源。

规则

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

三、springMVC集成Sentinel

这里用的是spring

<spring.version>5.3.18</spring.version>

<servlet.api.version>2.5</servlet.api.version> <sentinel.version>1.8.6</sentinel.version>

1、springmvc项目引入依赖pom

        <!-- 这是sentinel的核心依赖 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-core</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!-- 这是将自己项目和sentinel-dashboard打通的依赖 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!-- 这是使用sentinel对限流资源进行AOP -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-annotation-aspectj</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!--这是使用sentinel适配Web Servlet的依赖-->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-web-servlet</artifactId>
            <version>${sentinel.version}</version>
        </dependency>
        <!-- 这是使用sentinel热点参数限流功能依赖 -->
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-parameter-flow-control</artifactId>
            <version>${sentinel.version}</version>
        </dependency>

2、添加配置文件

在application.properties下创建同级文件sentinel.properties,内容如下

# 集成到sentinel的项目名称
project.name=spring-sentinel-demo
# 对应的sentinel-dashboard地址
csp.sentinel.dashboard.server=localhost:8080

3、添加配置类引入配置文件

创建配置类SentinelAspectConfiguration并引入配置文件sentinel.properties

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;

@Configuration
@PropertySources({@PropertySource("classpath:/sentinel.properties")})
public class SentinelAspectConfiguration {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}

4、web.xml新增如下过滤器配置

 <filter>
        <filter-name>SentinelCommonFilter</filter-name>
        <filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>SentinelCommonFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

接入 filter 之后,所有访问的 Web URL 就会被自动统计为 Sentinel 的资源—来源于 https://sentinelguard.io/zh-cn/docs/open-source-framework-integrations.html

开源框架适配的Web 适配下的Web Servlet

5、创建Controller接口

@Controller
public class WebMvcTestController {

    @GetMapping("/hello")
    @ResponseBody
    public String apiHello(String id) {
        System.out.println("id = " + id);
        Date date = new Date();
        System.out.println("date = " + date);
        return "Hello!";
    }

    @GetMapping("/doBusiness")
    @ResponseBody
    public String doBusiness(String id) {
        System.out.println("doBusiness = ");
        return "Oops...";
    }
 }

6、下载控制台-即图形化实时监控平台

参考 https://sentinelguard.io/zh-cn/docs/dashboard.html Sentinel 控制台的下载和启动

访问 https://github.com/alibaba/Sentinel/releases/tag/1.8.6

点击下载

7、运行控制台

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

运行控制台后运行springmvc项目,然后访问某一个路径,就可以在控制台看到了,实时监控如果这个路径没有被访问是显示不出来的

这个时候我们配置限流为即Qps为2

8、测试限流

这里我们用postman进行压测,填写请求的路径保存。并点击run调出压测执行器

执行后查看结果如下

四、自定义异常返回

1、定义如下接口(这里只进行了常见的url定义方式的定义)

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/test")
public class WebMvcTestController {
  
    /**
     * 1.未配置流控规则 1000次请求没有间隔发起请求,应该在1秒中完成09:44:33
     * @param id
     * @return
     */
    @RequestMapping("/RequestMapping")
    @ResponseBody
    public String RequestMapping(String id) {
        return "RequestMapping!";
    }

    @GetMapping("/GetMapping")
    @ResponseBody
    public String GetMapping(String id) {
        return "GetMapping...";
    }

    @PostMapping("/PostMapping")
    @ResponseBody
    public String PostMapping(String id) {
        return "PostMapping...";
    }

    /*
    * 路径变量(Path Variables):使用花括号 {} 来标记路径中的变量,并通过 @PathVariable 注解将其绑定到方法参数上
    * */
    @GetMapping("/GetMapping/{id}")
    @ResponseBody
    public String apiFoo(@PathVariable("id") Long id) {
        return "Hello " + id;
    }

    /*
    * Ant风格的路径匹配:
    *   使用 ? 表示任意单个字符,
    *   * 表示任意多个字符(不包含路径分隔符 /),
    *   ** 表示任意多个字符(包含路径分隔符 /)。
    * */
    @GetMapping("/Ant/*/{id}")
    @ResponseBody
    public String Ant(@PathVariable("id") Long id) {
        return "Ant " + id;
    }

    /*
    * 正则表达式路径匹配:使用 @RequestMapping 注解的 value 属性结合正则表达式来定义请求路径。
    * */
    @GetMapping(value = "/users/{id:\\d+}")
    @ResponseBody
    public String pattern(@PathVariable("id") int id) {
        return "Ant " + id;
    }
}



2、自定义限流返回处理Handler

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.context.ApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


public class SentinelExceptionHandler implements UrlBlockHandler {

    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String requestURI = request.getRequestURI();
        String url = request.getRequestURL().toString();
        System.out.println("servletPath = " + servletPath);
        System.out.println("requestURI = " + requestURI);
        System.out.println("url = " + url);
        if (contextPath == null) {
            contextPath = "";
        }
        ApplicationContext controllerApplicationContext = LiteFlowApplicationContext.getControllerApplicationContext();
        RequestMappingHandlerMapping handlerMapping = controllerApplicationContext.getBean(RequestMappingHandlerMapping.class);
        // 查找匹配的处理方法
        Class<?> returnType = null;
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMethods.entrySet()) {
            RequestMappingInfo requestMappingInfo = entry.getKey();
            HandlerMethod handlerMethod = entry.getValue();
            //匹配url
            if (requestMappingInfo.getPatternsCondition().getPatterns().contains(requestURI)) {
                System.out.println("Controller: " + handlerMethod.getBeanType().getName());
                System.out.println("Method: " + handlerMethod.getMethod().getName());
                System.out.println("getReturnType: " + handlerMethod.getMethod().getReturnType());
                returnType = handlerMethod.getMethod().getReturnType();
                break;
            }
            //匹配路径带参数的url
            UrlPathHelper pathHelper = new UrlPathHelper();
            String lookupPath = pathHelper.getPathWithinApplication(request);
            PatternsRequestCondition patternsCondition = requestMappingInfo.getPatternsCondition();
            if (patternsCondition != null && patternsCondition.getMatchingPatterns(lookupPath).size() > 0) {
                System.out.println("Controller1111: " + handlerMethod.getBeanType().getName());
                System.out.println("Method111: " + handlerMethod.getMethod().getName());
                System.out.println("getReturnType: " + handlerMethod.getMethod().getReturnType());
                returnType = handlerMethod.getMethod().getReturnType();
                break;
            }
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResponseData data = null;
        if (returnType != null) {
            if (returnType == String.class) {
                String str = "返回类型为字符串方法限流";
                httpServletResponse.getWriter().write(str);
                return;
            } else if (returnType == Integer.class) {
                httpServletResponse.getWriter().write(new Integer(1));
                return;
            } else if (returnType == Long.class) {
                httpServletResponse.getWriter().write(2);
                return;
            } else if (returnType == Double.class) {

            } else if (returnType == Boolean.class) {

            } else if (returnType == Float.class) {

            } else if (returnType == Byte.class) {

            }
        }
        //BlockException 异常接口,包含Sentinel的五个异常
        // FlowException 限流异常
        // DegradeException 降级异常
        // ParamFlowException 参数限流异常
        // AuthorityException 授权异常
        // SystemBlockException 系统负载异常
        if (e instanceof FlowException) {
            data = new ResponseData(-1, "流控规则被触发......");
        } else if (e instanceof DegradeException) {
            data = new ResponseData(-2, "降级规则被触发...");
        } else if (e instanceof AuthorityException) {
            data = new ResponseData(-3, "授权规则被触发...");
        } else if (e instanceof ParamFlowException) {
            data = new ResponseData(-4, "热点规则被触发...");
        } else if (e instanceof SystemBlockException) {
            data = new ResponseData(-5, "系统规则被触发...");
        }
        httpServletResponse.getWriter().write(JSON.toJSONString(data));
    }
}

3、使用自定义限流处理类

import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SentinelConfig {


    public SentinelConfig() {
        WebCallbackManager.setUrlBlockHandler(new SentinelExceptionHandler());
    }
}

4、配置限流并测试结果

当开启限流后访问触发自定义UrlBlockHandler后结果如下

访问对应得url后控制台打印

servletPath = /test/RequestMapping
requestURI = /test/RequestMapping
url = http://localhost:8081/test/RequestMapping
Controller: org.example.WebMvcTestController
Method: RequestMapping
getReturnType: class java.lang.String
servletPath = /test/GetMapping
requestURI = /test/GetMapping
url = http://localhost:8081/test/GetMapping
Controller: org.example.WebMvcTestController
Method: GetMapping
getReturnType: class java.lang.String
servletPath = /test/PostMapping
requestURI = /test/PostMapping
url = http://localhost:8081/test/PostMapping
Controller: org.example.WebMvcTestController
Method: PostMapping
getReturnType: class java.lang.String
servletPath = /test/GetMapping/4
requestURI = /test/GetMapping/4
url = http://localhost:8081/test/GetMapping/4
Controller1111: org.example.WebMvcTestController
Method111: apiFoo
getReturnType: class java.lang.String
servletPath = /test/Ant/a/5
requestURI = /test/Ant/a/5
url = http://localhost:8081/test/Ant/a/5
Controller1111: org.example.WebMvcTestController
Method111: Ant
getReturnType: class java.lang.String
servletPath = /test/users/5
requestURI = /test/users/5
url = http://localhost:8081/test/users/5
Controller1111: org.example.WebMvcTestController
Method111: pattern
getReturnType: class java.lang.String

5、页面效果如下

五、springboot集成Sentinel

因为springboot集成文章较多,这里不多做赘述

Sentinel 与 Spring Boot/Spring Cloud 的整合见 Sentinel Spring Cloud Starter。

作者:京东健康 马仁喜

来源:京东云开发者社区 转载请注明来源

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1271123.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SpringBoot Bean解析

Bean解析 IOC介绍 松耦合灵活性可维护 注解方式配置Bean 实现方式1: Component声明,直接类上进行添加注解, 同时保证包扫描能扫到即可实现方式2: 配置类中使用Bean Configuration public class BeanConfiguration implements SuperConfiguration{Bean("dog")Ani…

【开源】基于JAVA的大学计算机课程管理平台

项目编号&#xff1a; S 028 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S028&#xff0c;文末获取源码。} 项目编号&#xff1a;S028&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 实验课程档案模块2.2 实验资源模块2…

AtCoder Beginner Contest 330 A~F

A.Counting Passes(暴力) 题意&#xff1a; 给定 n n n个学生的分数&#xff0c;以及及格分 x x x &#xff0c;问多少人及格了。 分析&#xff1a; 暴力枚举&#xff0c;依次判断每个学生的分数即可。 代码&#xff1a; #include <bits/stdc.h> using namespace s…

Stability AI 新发布SDXL Turbo:一款实时文本到图像生成模型

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

Word异常退出文档找回怎么操作?4个正确恢复方法!

“刚刚我在用word编辑文档&#xff0c;但是突然word就显示异常了&#xff0c;然后莫名其妙就自动退出了&#xff0c;这可怎么办&#xff1f;我还有机会找回这些文档吗&#xff1f;” 当我们在使用Microsoft Word时&#xff0c;突然遭遇到程序异常退出的情况&#xff0c;可能会让…

四个方法,设置excel文件只读模式

由于excel文件经常用于数据文件&#xff0c;数据就需要特别保护&#xff0c;大家可能需要将文件设置为只读模式来保护数据不被修改&#xff0c;Excel文件想要设置为只读的方法有很多&#xff0c;今天分享四种方法给大家&#xff1a; 方法一&#xff1a;文件属性 右键点击文件…

面试篇之微服务(一)

目录 概览 1.什么是微服务&#xff1f; 2.微服务带来了哪些挑战&#xff1f; 3.现在有哪些流行的微服务解决方案&#xff1f; 这三种方案有什么区别吗&#xff1f; 4.说下微服务有哪些组件&#xff1f; 注册中心 5.注册中心是用来干什么的&#xff1f; 6.SpringCloud可…

Android Studio Giraffe-2022.3.1-Patch-3安装注意事项

准备工作&#xff1a; android studio下载地址&#xff1a;https://developer.android.google.cn/studio/releases?hlzh-cn gradle下载地址&#xff1a;https://services.gradle.org/distributions/ 比较稳定的网络环境&#xff08;比较android studio相关的依赖需要从谷歌那边…

spring cloud Eureka注册中心和Nacos注册中心

文章目录 Eureka注册中心.Eureka的结构和作用搭建eureka-server创建 服务引入eureka依赖编写启动类编写配置文件启动服务 服务注册1&#xff09;引入依赖2&#xff09;配置文件3&#xff09;启动多个user-service实例 服务发现1&#xff09;引入依赖2&#xff09;配置文件3&…

日本MF备案注册数据库-在线免费查询

在日本&#xff0c;药物主文件&#xff08;DMF&#xff09;称为“主文件”或“MF”。 药物主文件&#xff08;DMF&#xff09;系统允许活性药物成分&#xff08;API&#xff09;的制造商向日本审查机构&#xff08;PMDA&#xff09;提交API的详细信息&#xff08;制造方法、数…

免费的电脑AI写作工具-5款好用的智能AI写作软件

随着人工智能&#xff08;AI&#xff09;技术的不断进步&#xff0c;电脑AI写作已经成为现代写作领域的一项不可或缺的工具。通过深度学习和自然语言处理的融合&#xff0c;AI写作软件得以模拟人类的创造性和表达能力&#xff0c;为我们提供了快速、高效地生成优质文字内容的可…

硫酸钡行业分析:预计2028年将达到8.3亿美元

硫酸钡常用于消化道造影&#xff0c;据国内使用者报道&#xff0c;粗细不匀型硫酸钡&#xff0c;优于细而匀的硫酸钡。硫酸钡是一种用于白色颜料、纸张、橡胶、X光检查时使用的填充剂。具有低硬度、接近直角交叉的完全解理、高密度、遇盐酸不起泡沫的板状结晶&#xff0c;与类似…

论文阅读——SEEM

arxiv: 分割模型向比较灵活的分割的趋势的转变&#xff1a;封闭到开放&#xff0c;通用到特定、one-shot到交互式。From closed-set to open-vocabulary segmentation&#xff0c;From generic to referring segmentation&#xff0c;From one-shot to interactive segmentati…

微服务--06--Sentinel 限流、熔断

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 1.微服务保护雪崩问题服务保护方案1.1.请求限流1.2.线程隔离1.3.服务熔断 2.Sentinel2.1.介绍和安装官方网站&#xff1a;[https://sentinelguard.io/zh-cn/](https…

如何使用MES管理系统管理与统计员工绩效

MES管理系统解决方案在生产流程优化中发挥着至关重要的作用&#xff0c;特别是在员工绩效的统计与管理方面。本文深入探讨了MES管理系统如何通过多种方式&#xff0c;包括实时数据采集、生产过程可视化、以及绩效指标设定与评估&#xff0c;以更精准、全面的方式统计员工绩效&a…

儿童绘本故事之乐小鱼的龙舟体验

《乐小鱼的龙舟体验》 Chapter 1: 破浪前行的盛宴在2023年11月26日的清晨&#xff0c;顺德迎来了一场震撼心灵的盛宴——中国龙舟大奖赛。湖面上&#xff0c;龙舟竞渡&#xff0c;破浪前行&#xff0c;为这座城市注入了一份激情的节奏。On the morning of November 26, 2023, …

JSON 与 FastJSON

JSON 与 FastJSON JSON JavaScript Object Notation&#xff08;JavaScript 对象表示法&#xff09;是目前最常用的执行对象序列化的方式。 虽然 json 最初是为了在 JavaScript 语言中使用的&#xff0c;但实际上 json 本身跟语言没有任何关系&#xff0c;各种编程语言都可以使…

广州华锐视点:3D毒品预防专题教育平台帮助青少年提升拒毒意识

随着科技的不断发展&#xff0c;人们的生活方式也在不断地改变。在这个信息爆炸的时代&#xff0c;传统的普法教育方式已经无法满足人们的需求。为了适应这一变化&#xff0c;越来越多的教育机构开始尝试利用现代科技手段进行普法教育。其中&#xff0c;3D毒品预防专题教育平台…

C++基础 -21-多继承与多级继承

多继承 代码示例 #include "iostream"using namespace std;class base1 { public:base1() {}base1(int a, int b) : a(a), b(b) {}int a;protected:int b; };class base2 { public:base2() {}base2(int a, int b) : c(a), d(b) {}int c;protected:int d; };class …

开启虾皮购物新旅程,快速注册买家号

想要在shopee上畅享丰富的购物体验吗&#xff1f;那就让我们一起迈出第一步&#xff0c;注册一个属于你自己的虾皮买家号吧&#xff01; 1. 访问虾皮平台 首先&#xff0c;打开你的浏览器&#xff0c;输入虾皮平台网址&#xff0c;点击注册或登录按钮。这将引导你进入注册界面…