当前位置: 首页 > news >正文

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搭建

下载地址

  • https://github.com/alibaba/Sentinel/releases/download/1.8.6/sentinel-dashboard-1.8.6.jar

运行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 {@AutowiredTestService 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 {@Beanpublic 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);}}

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

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.

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看结果

11

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

5.引用

  • https://sentinelguard.io/zh-cn/docs/quick-start.html
  • Spring Boot如何替换默认的sentinel服务器? | Harries Blog™

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • SQL之使用存储过程循环插入数据
  • OSPF笔记
  • 搭建高可用OpenStack(Queen版)集群(十一)之OpenStack集成ceph服务
  • opencv 多线程分块处理
  • FFmpeg源码:packet_alloc、av_new_packet、av_shrink_packet、av_grow_packet函数分析
  • 掌握NPM版本候选锁定:策略、实践与示例
  • 如果你懂开发,我真心劝你来试试网络安全
  • 自由职业四年,我整理了一些建议
  • 【数据结构】堆排序与TOP-K问题
  • Naive UI+vue一些组件的注意事项
  • element plus el-select修改后缀图标
  • 【双向链表】的建立、插入、删除、查找和销毁
  • 量化策略开发步骤系列(3)关键投资组合指标
  • firefly推理和微调qwen
  • Appium基础
  • [iOS]Core Data浅析一 -- 启用Core Data
  • Angular数据绑定机制
  • JS变量作用域
  • k8s 面向应用开发者的基础命令
  • passportjs 源码分析
  • SegmentFault 技术周刊 Vol.27 - Git 学习宝典:程序员走江湖必备
  • SpiderData 2019年2月23日 DApp数据排行榜
  • Sublime text 3 3103 注册码
  • Webpack 4 学习01(基础配置)
  • 诡异!React stopPropagation失灵
  • 微信小程序:实现悬浮返回和分享按钮
  • 微信小程序上拉加载:onReachBottom详解+设置触发距离
  • 为视图添加丝滑的水波纹
  • 【云吞铺子】性能抖动剖析(二)
  • 翻译 | The Principles of OOD 面向对象设计原则
  • ​补​充​经​纬​恒​润​一​面​
  • ​油烟净化器电源安全,保障健康餐饮生活
  • ### RabbitMQ五种工作模式:
  • #gStore-weekly | gStore最新版本1.0之三角形计数函数的使用
  • #我与Java虚拟机的故事#连载16:打开Java世界大门的钥匙
  • ()、[]、{}、(())、[[]]等各种括号的使用
  • (done) 两个矩阵 “相似” 是什么意思?
  • (LLM) 很笨
  • (非本人原创)我们工作到底是为了什么?​——HP大中华区总裁孙振耀退休感言(r4笔记第60天)...
  • (分布式缓存)Redis持久化
  • (过滤器)Filter和(监听器)listener
  • (黑客游戏)HackTheGame1.21 过关攻略
  • (学习总结16)C++模版2
  • (已解决)什么是vue导航守卫
  • ..回顾17,展望18
  • ./configure、make、make install 命令
  • .NET Conf 2023 回顾 – 庆祝社区、创新和 .NET 8 的发布
  • .NET 程序如何获取图片的宽高(框架自带多种方法的不同性能)
  • .Net 垃圾回收机制原理(二)
  • .net 写了一个支持重试、熔断和超时策略的 HttpClient 实例池
  • .NET/C# 编译期间能确定的相同字符串,在运行期间是相同的实例
  • .NET程序集编辑器/调试器 dnSpy 使用介绍
  • .NET设计模式(11):组合模式(Composite Pattern)
  • @Autowired和@Resource的区别
  • @Autowired自动装配