springboot接入sentinel案例

版本控制

  • springboot: 3.3.2
  • spring-cloud-starter-alibaba-sentinel: 2023.0.3.2
  • sentinel-dashboard: 1.8.8

项目源代码

  • 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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.dubbo</groupId>
    <artifactId>sentinel_demo2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sentinel_demo2</name>
    <description>sentinel_demo2</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>21</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2023.0.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <!--针对 web 接口流控,所有接口都被定义为资源-->
        <!--<dependency>-->
        <!--    <groupId>com.alibaba.csp</groupId>-->
        <!--    <artifactId>sentinel-web-servlet</artifactId>-->
        <!--    <version>1.8.8</version>-->
        <!--</dependency>-->

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

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

</project>
  • application.yml
yml 复制代码
spring.application.name=sentinel_demo667
server.port=8081

#csp.sentinel.dashboard.server=127.0.0.1:8080
#csp.sentinel.heartbeat.client.ip=10.17.0.19
#csp.sentinel.api.port=8719

spring.cloud.sentinel.transport.dashboard=127.0.0.1:8080
spring.cloud.sentinel.transport.port=8719
spring.cloud.sentinel.transport.client-ip=10.17.0.19
  • 配置AopConfiguration
java 复制代码
import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Eric Zhao
 */
@Configuration
public class AopConfiguration {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }
}
  • 接口
java 复制代码
import com.dubbo.sentinel_demo2.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author lihw
 * @Date 2025/1/6 上午9:40
 */
@RestController
public class DemoController {
    @Autowired
    private TestService service;

    @GetMapping("/foo")
    public String apiFoo(@RequestParam(required = false) Long t) throws Exception {
        if (t == null) {
            t = System.currentTimeMillis();
        }
        service.test();
        return service.hello(t);
    }

    @GetMapping("/baz/{name}")
    public String apiBaz(@PathVariable("name") String name) {
        return service.helloAnother(name);
    }

    @GetMapping("/test")
    public String test() {
        service.test();
        return "succ";
    }
}
  • 服务
  • TestService
java 复制代码
/**
 * @Description TODO
 * @Author lihw
 * @Date 2025/1/6 上午9:22
 */
public interface TestService {
    void test();

    String hello(long s);

    String helloAnother(String name);
}
  • TestServiceImpl
java 复制代码
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import org.springframework.stereotype.Service;

/**
 * @author Eric Zhao
 */
@Service
public class TestServiceImpl implements TestService {

    @Override
    @SentinelResource(value = "test", blockHandler = "handleException", blockHandlerClass = {ExceptionUtil.class})
    public void test() {
        System.out.println("Test");
    }

    @Override
    @SentinelResource(value = "hello", fallback = "helloFallback")
    public String hello(long s) {
        if (s < 0) {
            throw new IllegalArgumentException("invalid arg");
        }
        return String.format("Hello at %d", s);
    }

    @Override
    @SentinelResource(value = "helloAnother", defaultFallback = "defaultFallback",
            exceptionsToIgnore = {IllegalStateException.class})
    public String helloAnother(String name) {
        if (name == null || "bad".equals(name)) {
            throw new IllegalArgumentException("oops");
        }
        if ("foo".equals(name)) {
            throw new IllegalStateException("oops");
        }
        return "Hello, " + name;
    }

    public String helloFallback(long s, Throwable ex) {
        // Do some log here.
        ex.printStackTrace();
        return "Oops, error occurred at " + s;
    }

    public String defaultFallback() {
        System.out.println("Go to default fallback");
        return "default_fallback";
    }
}
  • ExceptionUtil
java 复制代码
import com.alibaba.csp.sentinel.slots.block.BlockException;

/**
 * @author Eric Zhao
 */
public final class ExceptionUtil {

    public static void handleException(BlockException ex) {
        // Handler method that handles BlockException when blocked.
        // The method parameter list should match original method, with the last additional
        // parameter with type BlockException. The return type should be same as the original method.
        // The block handler method should be located in the same class with original method by default.
        // If you want to use method in other classes, you can set the blockHandlerClass
        // with corresponding Class (Note the method in other classes must be static).
        System.out.println("Oops: " + ex.getClass().getCanonicalName());
    }
}

注意事项:

sentinel控制台启动之后,springboot客户端不会立刻去注册,而是等请求过来之后再去控制台注册。【懒加载】

此时未接入sentinel持久化配置,在sentinel服务端重启之后,所有在服务端配置的流控规则就会失效。

相关推荐
羊小猪~~11 分钟前
MYSQL学习笔记(九):MYSQL表的“增删改查”
数据库·笔记·后端·sql·学习·mysql·考研
豌豆花下猫27 分钟前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai
橘猫云计算机设计1 小时前
基于SSM的《计算机网络》题库管理系统(源码+lw+部署文档+讲解),源码可白嫖!
java·数据库·spring boot·后端·python·计算机网络·毕设
小盼江1 小时前
水果生鲜农产品推荐系统 协同过滤余弦函数推荐水果生鲜农产品 Springboot Vue Element-UI前后端分离 代码+开发文档+视频教程
vue.js·spring boot·ui
熬夜苦读学习1 小时前
Linux文件系统
linux·运维·服务器·开发语言·后端
坚定信念,勇往无前1 小时前
Spring Boot中整合Flink CDC 数据库变更监听器来实现对MySQL数据库
数据库·spring boot·flink
坚定信念,勇往无前2 小时前
Spring Boot 如何保证接口安全
spring boot·后端·安全
程序员侠客行3 小时前
Spring事务原理详解 三
java·后端·spring·架构
尚学教辅学习资料3 小时前
基于SpringBoot+Vue+uniapp的高校招聘小程序+LW参考示例
spring boot·uni-app·招聘系统
zfj3213 小时前
手动搭建Redis1主2从+ 3 Sentinel 高可用集群
redis·sentinel·高可用