Master Sentinel Flow Control: Dashboard Setup, RestTemplate & OpenFeign Integration

This guide walks you through installing the Sentinel dashboard, configuring flow‑control rules, and integrating Sentinel with Spring Cloud's RestTemplate and OpenFeign to protect microservice endpoints using QPS limits and fallback strategies.

Ops Development Stories
Ops Development Stories
Ops Development Stories
Master Sentinel Flow Control: Dashboard Setup, RestTemplate & OpenFeign Integration

In a previous article we gave a brief introduction to Sentinel; this article focuses on practical usage, including installing the Sentinel dashboard, configuring flow‑control rules, and integrating Sentinel with RestTemplate and OpenFeign.

Install Sentinel Dashboard

We use sentinel-dashboard-1.8.0. Start the console with: java -jar sentinel-dashboard-1.8.0.jar The dashboard runs on port 8080 by default, with username and password both set to sentinel. To change the port, add -Dserver.port=9999 to the command.

Usage Introduction

The most common scenario is adding flow‑control rules to protect API interfaces; Sentinel also provides support for RestTemplate and OpenFeign.

Simple Example

1. Import Dependencies

Add the Sentinel client starter to your service:

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

Version information for spring-boot, spring-cloud and spring-cloud-alibaba can be managed as follows:

<properties>
  <spring-boot.version>2.3.10.RELEASE</spring-boot.version>
  <spring-cloud.version>Hoxton.SR8</spring-cloud.version>
  <spring-cloud-alibaba.version>2.2.5.RELEASE</spring-cloud-alibaba.version>
</properties>

<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>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-dependencies</artifactId>
      <version>${spring-cloud.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>

2. YML Configuration

After adding the dependency, configure application.yml so the service registers with the dashboard:

spring:
  cloud:
    sentinel:
      transport:
        port: 8719
        dashboard: localhost:8080

3. Test Interface Definition

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "OK";
    }
}

4. Configure Flow Rules via Console

Note: If the dashboard shows no services after both the dashboard and the business service are started, first invoke a service endpoint, then refresh the dashboard. Also ensure the client version matches the dashboard version.

Select the service, go to the Cluster Link menu, choose the /hello interface, and click the Flow Control button.

Set the rule to QPS type, single‑machine threshold 1. When the threshold is exceeded, Sentinel returns Blocked by Sentinel (flow limiting).

sentinel flow rule configuration 1
sentinel flow rule configuration 1
sentinel flow rule configuration 2
sentinel flow rule configuration 2

5. Flow Rule Trigger

Repeatedly calling /hello will trigger the rule:

~ curl http://127.0.0.1:8066/hello
OK
~ curl http://127.0.0.1:8066/hello
Blocked by Sentinel (flow limiting)

Integrate RestTemplate

1. YML Configuration

resttemplate:
  sentinel:
    enabled: true

2. Create RestTemplate

@Configuration
public class RestTemplateConfig {
    @Bean
    @ConditionalOnMissingBean(RestTemplate.class)
    @LoadBalanced
    @SentinelRestTemplate(blockHandler = "handlerException", blockHandlerClass = SentinelExceptionHandler.class,
                         fallback = "handleFallback", fallbackClass = SentinelExceptionHandler.class)
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

public class SentinelExceptionHandler {
    // Flow‑control business logic
    public static SentinelClientHttpResponse handlerException(HttpRequest request, byte[] body,
                                                            ClientHttpRequestExecution execution, BlockException ex) {
        String message = JSON.toJSONString(CommonResult.error(-100, "系统错误 (限流熔断业务逻辑)"));
        return new SentinelClientHttpResponse(message);
    }
    // Fallback business logic
    public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body,
                                                            ClientHttpRequestExecution execution, BlockException ex) {
        String message = JSON.toJSONString(CommonResult.error(-100, "系统错误 (异常降级业务逻辑)"));
        return new SentinelClientHttpResponse(message);
    }
}

3. Interface Definition

Use the configured RestTemplate to call stock-service ’s /getStockDetail endpoint and wrap the result in a CommonResult<StockModel> object.

@Autowired
private RestTemplate restTemplate;

@GetMapping("/hello2")
public CommonResult<OrderModel> hello2() {
    ParameterizedTypeReference<CommonResult<StockModel>> typeRef = new ParameterizedTypeReference<>() {};
    ResponseEntity<CommonResult<StockModel>> forEntity =
        restTemplate.exchange("http://stock-service/getStockDetail", HttpMethod.GET,
                             HttpEntity.EMPTY, typeRef);
    OrderModel orderModel = new OrderModel();
    orderModel.setId(100);
    orderModel.setCode("100-100");
    if (forEntity.getStatusCode() == HttpStatus.OK && forEntity.getBody() != null) {
        CommonResult<StockModel> result = forEntity.getBody();
        if (result.getCode() != 1) {
            return CommonResult.error(null, result.getCode(), result.getMessage());
        }
        orderModel.setStockModel(result.getData());
    }
    return CommonResult.success(orderModel);
}

4. Flow Trigger

~ curl http://127.0.0.1:8066/hello2
{"code":1,"message":"this is a success message","data":{"id":100,"code":"100-100","stockModel":{"id":1,"code":"STOCK==>1000"}}}
~ curl http://127.0.0.1:8066/hello2
{"code":-100,"message":"系统错误 (限流熔断业务逻辑)","data":null}

Integrate OpenFeign

1. Import OpenFeign Dependency

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2. YML Configuration

feign:
  sentinel:
    enabled: true

Add @EnableFeignClients to the main application class to activate OpenFeign.

3. Call Code

Define a Feign client for stock-service:

@FeignClient(name = "stock-service", fallbackFactory = StockFeignFallbackFactory.class)
public interface StockFeign {
    @GetMapping("/getStockDetail")
    CommonResult<StockModel> getStockDetail();
}

Provide a fallback factory for degradation:

@Component
public class StockFeignFallbackFactory implements FallbackFactory<StockFeign> {
    private Logger log = LoggerFactory.getLogger(StockFeignFallbackFactory.class);
    @Override
    public StockFeign create(Throwable throwable) {
        return new StockFeign() {
            @Override
            public CommonResult<StockModel> getStockDetail() {
                log.error("调用查询库存详情降级", throwable);
                return CommonResult.error(null, -100, "调用查询库存详情降级");
            }
        };
    }
}

Controller uses the Feign client:

@Autowired
private StockFeign stockFeign;

@GetMapping("/hello1")
public CommonResult<OrderModel> hello() {
    CommonResult<StockModel> result = stockFeign.getStockDetail();
    if (result.getCode() != 1) {
        return CommonResult.error(null, result.getCode(), result.getMessage());
    }
    StockModel stockDetail = result.getData();
    OrderModel orderModel = new OrderModel();
    orderModel.setStockModel(stockDetail);
    return CommonResult.success(orderModel);
}

4. Business Execution

Frequent calls to /hello1 will trigger the fallback:

~ curl http://127.0.0.1:8066/hello1
{"code":1,"message":"this is a success message","data":{"id":null,"code":null,"stockModel":{"id":1,"code":"STOCK==>1000"}}}
~ curl http://127.0.0.1:8066/hello1
{"code":-100,"message":"调用查询库存详情降级","data":null}

Source Code Repository

gitee: https://gitee.com/zhengsh/excavator

References

https://spring-cloud-alibaba-group.github.io/github-pages/hoxton/en-us/index.html#_spring_cloud_alibaba_sentinel

https://segmentfault.com/a/1190000019070557

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.

JavaMicroservicessentinelSpring CloudresttemplateFlow Control
Ops Development Stories
Written by

Ops Development Stories

Maintained by a like‑minded team, covering both operations and development. Topics span Linux ops, DevOps toolchain, Kubernetes containerization, monitoring, log collection, network security, and Python or Go development. Team members: Qiao Ke, wanger, Dong Ge, Su Xin, Hua Zai, Zheng Ge, Teacher Xia.

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.