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服务端重启之后,所有在服务端配置的流控规则就会失效。

相关推荐
DevOpsDojo6 分钟前
Bash语言的函数实现
开发语言·后端·golang
Upuping7 分钟前
Servlet详解
java·后端·web
DevOpsDojo9 分钟前
Bash语言的软件工程
开发语言·后端·golang
华年源码15 分钟前
基于springboot的房屋租赁系统(源码+数据库+文档)
java·数据库·spring boot·后端·毕业设计·源码·springboot
CodeChampion23 分钟前
68.基于SpringBoot + Vue实现的前后端分离-心灵治愈交流平台系统(项目 + 论文PPT)
java·vue.js·spring boot·mysql·elementui·node.js·idea
云端 架构师23 分钟前
Elixir语言的正则表达式
开发语言·后端·golang
kay53531 分钟前
编排式 Saga 模式
java·spring boot
2401_8984106944 分钟前
Bash语言的编程范式
开发语言·后端·golang
荆州克莱1 小时前
【Azure Redis 缓存】Azure Redis 遇见的连接不上问题和数据丢失的情况解答
spring boot·spring·spring cloud·css3·技术
SyntaxSage1 小时前
Ruby语言的多线程编程
开发语言·后端·golang