Master Sentinel Flow Control: Dashboard, RestTemplate & OpenFeign Integration

This guide demonstrates how to install Sentinel Dashboard, configure flow‑control rules, and integrate Sentinel with Spring Cloud’s RestTemplate and OpenFeign, providing Maven dependencies, YAML settings, sample controller code, and fallback handling to protect microservice APIs from overload.

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

In a previous article we introduced Sentinel; this article explains how to use Sentinel, configure flow‑control rules via the sentinel‑dashboard, and integrate 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 Default port is 8080, default username and password are sentinel. To change the port add -Dserver.port=9999 before the command.

Usage introduction

The most common scenario is adding flow‑control rules for API interfaces. Sentinel also supports RestTemplate and OpenFeign.

Simple example

1. Import dependencies

Add the Maven dependency for the Sentinel client:

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

Version properties for Spring Boot, Spring Cloud, and Spring Cloud Alibaba:

<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

Register the service with the dashboard in application.yml:

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 rule via console

In the dashboard select the service, go to the "Cluster Link" menu, choose the /hello interface, and click the "Flow Control" button. Set the rule type to QPS and the threshold to 1, meaning the interface can handle only one request per second. When the limit is exceeded Sentinel returns "Blocked by Sentinel (flow limiting)".

Configuration screenshots:

5. Flow rule trigger

Repeatedly calling /hello triggers 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 {
    public static SentinelClientHttpResponse handlerException(HttpRequest request, byte[] body,
        ClientHttpRequestExecution execution, BlockException ex) {
        String message = JSON.toJSONString(CommonResult.error(-100, "系统错误 (限流熔断业务逻辑)"));
        return new SentinelClientHttpResponse(message);
    }
    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

Example code that calls stock-service via RestTemplate and wraps the result:

@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 (Objects.equals(forEntity.getStatusCode(), HttpStatus.OK) && Objects.nonNull(forEntity.getBody())) {
        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 enable OpenFeign.

3. Feign client definition

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

4. Fallback factory

@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, "调用查询库存详情降级");
            }
        };
    }
}

5. Controller usage

@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);
}

6. Business execution

Repeated calls to /hello1 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 address

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.

OpenFeign
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.