Integrating Alibaba Sentinel with Spring Boot for API Flow Control

This step‑by‑step guide shows how to set up the Sentinel dashboard, add the Sentinel client to a Spring Boot project, define protected resources programmatically or with annotations, start the dashboard, and configure flow‑control and degradation rules to limit API traffic.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Integrating Alibaba Sentinel with Spring Boot for API Flow Control

Setting Up the Sentinel Dashboard

Start the Sentinel dashboard by running the provided jar with the required JVM options. Example command:

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

Adding the Sentinel Client to a Spring Boot Project

Project Initialization

Create a Spring Boot project (e.g., via start.aliyun.com) and enable the Sentinel starter during the wizard.

Add the following Maven dependency (version managed by the Alibaba Cloud parent BOM):

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

If the Alibaba Cloud repository is used, the parent spring-cloud-alibaba-dependencies BOM provides the correct version, so an explicit <version> tag is unnecessary.

Include the BOM in dependencyManagement:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>${spring-cloud-alibaba.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Configure the client to connect to the dashboard and enable eager initialization (optional client‑IP override):

server.port=8083
spring.application.name=springcloud-sentinel
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.eager=true
# spring.cloud.sentinel.transport.client-ip=YOUR_IP   (uncomment if automatic detection fails)

Defining Resources

Programmatic Definition

Define a flow rule in Java and protect a resource named HelloWorld. The example creates a rule that limits QPS to 20 and registers it with FlowRuleManager. The main loop repeatedly calls the protected entry.

package com.milo.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 java.util.ArrayList;
import java.util.List;

@SpringBootApplication
public class SentinelApplication {
    public static void main(String[] args) {
        SpringApplication.run(SentinelApplication.class, args);
        initFlowRules();
        while (true) {
            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);
        rule.setCount(20); // QPS limit
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}

Annotation‑Based Definition

Use the @SentinelResource annotation to mark a Spring bean method as a protected resource. The resource name is supplied via the value attribute.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

@Service
public class TestService {
    @SentinelResource(value = "sayHello")
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

@RestController
public class TestController {
    @Autowired
    private TestService service;

    @GetMapping("/hello/{name}")
    public String apiHello(@PathVariable String name) {
        return service.sayHello(name);
    }
}

Configuring Rules in the Dashboard

After the application starts, it appears under the machine list in the dashboard (e.g., springcloud-sentinel). Selecting the instance shows real‑time metrics, cluster topology, and rule configuration panels.

Flow‑Control Rule

Create a flow rule for the HelloWorld resource with QPS = 1. The dashboard visualizes the rule and enforces the limit immediately; the real‑time monitor reflects the throttled traffic.

Degradation Rule

Add a degradation rule for HelloWorld that triggers when QPS exceeds 1 and the average response time exceeds 20 ms. The rule blocks the resource for 2 seconds before automatic recovery.

Note: Rules configured through the dashboard are stored only in memory; they are lost when the application restarts. Persistent rule storage requires additional configuration (e.g., Nacos, Redis) which is covered in later articles.

For complete reference, see the official Sentinel dashboard documentation at https://sentinelguard.io/zh-cn/docs/dashboard.html.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaMicroservicesSpring BootsentinelAPI Flow Control
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.