This project demonstrates how to use Sentinel to complete fuse downcall for Spring Cloud applications.

Sentinel is the flow defense component of Alibaba’s open source distributed system. Sentinel takes the flow as the entry point to protect the stability of services from multiple dimensions such as flow control, fuse downgrading and system load protection.

OpenFeign is a declarative, template-based HTTP client. Feign can help you call HTTP APIS more quickly and elegantly. You need to know the basics of OpenFeign, please refer to the source code of cloud-Feign example.

The service registry of this project uses NACOS, and the service provider uses Spring Cloud Alibaba

Sentinel introduces

With the popularity of microservices, stability between services becomes increasingly important. Sentinel takes flow as the entry point to protect the stability of service from multiple dimensions such as flow control, fusing downgrading and system load protection.

Sentinel has the following characteristics:

  • 1. Rich application scenarios

Sentinel follows alibaba’s core traffic driving scenarios in the past 10 years, such as SEC killing (i.e. burst traffic control within the range of system capacity), message peaking and valley filling, cluster flow control, real-time fusing of downstream unavailable applications, etc.

  • 2. Complete real-time monitoring

Sentinel also provides real-time monitoring capabilities. From the console, you can see a summary of the performance of a single machine-by-second data, or even a cluster of less than 500 machines, for accessing the application.

  • 3. Extensive open source ecosystem

Sentinel provides out-of-the-box integration modules with other open source frameworks/libraries, such as Spring Cloud, Dubbo, and gRPC. You can quickly access Sentinel by introducing the appropriate dependencies and simple configuration.

  • 4. Complete SPI extension points

Sentinel provides an easy-to-use, comprehensive SPI extension interface. You can quickly customize the logic by implementing an extension interface. For example, customize rule management and adapt dynamic data sources.

Sentinel is divided into two parts

  • The core library (Java client) is independent of any framework/library, can run in all Java runtime environments, and has good support for frameworks such as Dubbo/Spring Cloud.
  • The Console (Dashboard) is based on Spring Boot and can be packaged to run directly without the need for additional application containers such as Tomcat.

Main characteristics of Sentinel

Sentinel Open Source ecology

Fusing the drop

Fusible downgrading of unstable resources in call links is one of the important measures to ensure high availability. Because of the complexity of the invocation relationship, if a resource in the invocation link is unstable, requests will eventually pile up. Sentinel fuse degradation limits the invocation of a resource when unstable status (such as call timeout or abnormal proportion increases) occurs in the invocation link, so that the request fails quickly and avoids cascading errors caused by affecting other resources. When a resource is degraded, all calls to the resource will automatically fuse within the next degraded window (default behavior is to throw a DegradeException).

Demotion strategy

  • Average response time (DEGRADE_GRADE_RT) : When five requests arrive within 1s and the response time exceeds the threshold of count (ms), the degradability of the response time is reduced to s. Calls to this method will automatically fuse (throw a DegradeException).
  • DEGRADE_GRADE_EXCEPTION_RATIO: A resource degrades when the number of requests per second is greater than or equal to 5 and the ratio of exception_requests per second to the total volume of passes exceeds the threshold (count).
  • Number of exceptions (DEGRADE_GRADE_EXCEPTION_COUNT) : When the number of exceptions in the last 1 minute exceeds the threshold, a resource is fused.

Fuse downgrade code implementation

Service Provider

Create the Ali-nacos-Provider project

  1. First, rely on the NACOS registry
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
  1. Define the service provider interface
@RestController
@Slf4j
public class HelloController {
    @GetMapping(value = "/hello/{str}", produces = "application/json")
    public String hello(@PathVariable String str) {
        log.info("----------- Received consumer request -----------");
        log.info("Received parameters from consumer:" + str);
        String result = "I'm a service provider. Nice to meet you." + str;
        log.info("Provider returns result:" + result);
        returnresult; }}Copy the code

Service and consumer

Create the Ali-Nacos-Sentinel-Feign project

1. First, pom.xml adds dependencies

    <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-nacos-discovery</artifactId>
        </dependency>

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

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

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

    </dependencies>
Copy the code

2. Define FeignClient and degrade it

  • Define FeignClient
package com.easy.ansFeign.service;

import com.easy.ansFeign.fallback.HelloServiceFallbackFactory;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@FeignClient(name = "ali-nacos-provider", fallbackFactory = HelloServiceFallbackFactory.class)
public interface HelloService {

    /** * invokes the service provider's output interface. **@paramSTR The user enters *@return hello result
     */
    @GetMapping("/hello/{str}")
    String hello(@PathVariable("str") String str);
}

Copy the code
  • Define the Fallback factory to get the exception
@Component
public class HelloServiceFallbackFactory implements FallbackFactory<HelloServiceFallback> {

    @Override
    public HelloServiceFallback create(Throwable throwable) {
        return newHelloServiceFallback(throwable); }}Copy the code
  • Define the concrete fallback implementation
public class HelloServiceFallback implements HelloService {

    private Throwable throwable;

    HelloServiceFallback(Throwable throwable) {
        this.throwable = throwable;
    }

    /** * invokes the service provider's output interface. **@paramSTR The user enters *@return* /
    @Override
    public String hello(String str) {
        return "Service invocation failed, degraded processing. Exception message:"+ throwable.getMessage(); }}Copy the code
  • Test the entrance
@RestController
public class TestController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/hello-feign/{str}")
    public String feign(@PathVariable String str) {
        returnhelloService.hello(str); }}Copy the code

Use the sample

Sample associated project

On the basis of how Spring Cloud Alibaba (I) uses NACOS service registration and discovery, we create ali-Nacos-Sentinel-Feign project and invoke ali-nacos-Provider project as the service provider of this example. The following two items are tested.

Ali-nacos-provider: service provider, service name: Ali-nacos-Provider, port: 9000 Ali-NACos-Sentinel-Feign: service consumer, service name: Ali-nacos-Sentinel-Feign, port: 9102

Run the sample tests

The service registry NACOS, Ali-nacOS-Provider service and Ali-Nacos-Sentinel-Feign service should be started first

  • Access the address: http://localhost:9102/hello-feign/yuntian

return

I'm a service provider. Nice to meet youCopy the code

Our service was successfully invoked

  • Close ali – nacos – the provider services, visit: http://localhost:9102/hello-feign/yuntian

return

Service invocation failed, degraded processing. Abnormal information: com.net flix. Client. ClientException: the Load balancer does not have the available server for the client: ali - nacos - the providerCopy the code

Indicates that our scheduled callback was executed and the service was successfully degraded.

data

  • Spring Cloud Alibaba Sentinel example source code
  • The original address
  • Sentinel GitHub