Alibaba Sentinel integrates SpringBoot to protect microservices!

 foreword

        With the popularity of microservices, the stability between services and services has become more and more important. Sentinel is a traffic management component for distributed, multilingual and heterogeneous service architectures. It mainly takes traffic as the entry point, and provides various services from traffic routing, traffic control, traffic shaping, circuit breaker downgrading, system adaptive overload protection, hotspot traffic protection, etc. dimensions to help developers ensure the stability of microservices.


text

1.  Sentinel features

        Sentinel takes traffic as the entry point, and protects the stability of services from multiple dimensions such as traffic control, circuit breaker degradation, and system load protection.

        Sentinel has the following characteristics:

  1.  Rich application scenarios: Sentinel  has undertaken the core scenarios of Alibaba’s Double Eleven traffic promotion in the past 10 years, such as seckill (that is, burst traffic is controlled within the range that the system 
  2. Complete real-time monitoring: Sentinel  also provides real-time monitoring functions . In the console, you can see the second-level data of a single machine connected to the application,  or even the aggregated running status of a cluster with a scale of less than 500 .
  3. Extensive open source ecosystem: Sentinel  provides out-of-the-box integration modules with other open source frameworks / libraries, such as integration with Spring Cloud  , Dubbo , and  gRPC  . You only need to introduce the corresponding dependencies and perform simple configurations to quickly access Sentinel .
  4. Perfect SPI  extension point:    Sentinel  provides easy -to-use and complete SPI  extension point. You can quickly customize logic by implementing extension points.  For example, customizing rule management, adapting data sources, etc.

        Alibaba Cloud provides the enterprise-level Sentinel  service and applies the high-availability service AHAS.

Comparison between        Sentinel and Hystrix :

Sentinel Hystrix
isolation strategy Semaphore isolation Thread pool isolation/semaphore isolation
Circuit breaker downgrade strategy Based on response time or failure rate Based on failure rate
Real-time indicator implementation sliding window Sliding window (based on RxJava)
rule configuration Support multiple data sources Support multiple data sources
Scalability multiple extension points plug-in form
Annotation-based support support support
Limiting Based on QPS, support current limiting based on call relationship limited support
traffic shaping Support full start, uniform speed mode not support
System load protection support not support
console

Out of the box, you can configure rules, view second-level monitoring, machine discovery, etc.

not support
Adaptation to Common Frameworks Servlet,Spring Cloud,Dubbo,gRPC等 Servlet,Spring Cloud Netflix

        Both Sentinel and Hystrix are open source, but the Netflix team of Hystrix is ​​no longer maintained, and the Sentinel Ali team has been iteratively updating, and the community is also constantly developing.

        In terms of performance, Sentinel is lighter than Hystrix and has better performance, and it has passed the test of the huge traffic of Double Eleven Ali.


2.  Sentinel Quick Start

2.1 API implementation

  • Introduce dependencies

<dependency>

        <groupId>com.alibaba.csp</groupId>

        <artifactId>sentinel core</artifactId>

        <version>1.8.0</version>

</dependency>

  • Code

        In the official document, the defined Sentinel needs to define resources and rules for resource protection.

@Slf4j
@RestController
@RequestMapping(value = "/sentinel")
public class TestSentinelController {

    private static final String RESOURCE_NAME	=	"hello";

    /**
     *	编写测试代码,对"hello"进行资源保护
     */
    @RequestMapping(value = "/hello")
    public String hello() {

        Entry entry = null;
        try {
            // 资源名可使用任意有业务语义的字符串,比如方法名、接口名或其它可唯一标识的字符串。
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String str	=	"hello world";
            log.info("====="+str);
            return str;
        } catch (BlockException e1) {
            // 资源访问阻止,被限流或被降级
            // 进行相应的处理操作
            log.info("block!");
        } catch (Exception ex) {
            // 若需要配置降级规则,需要通过这种方式记录业务异常
            Tracer.traceEntry(ex, entry);
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return null;
    }
    /**
     *	定义流控规则
     */
    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules	=	new ArrayList<>();
        FlowRule rule = new FlowRule();
        // 设置受保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        // Set limit QPS to 20.
        rule.setCount(1);
        // 加载配置好的规则
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
  • Test effect

  •  shortcoming
  1. The business is very intrusive, and non-business code needs to be written in the controller ;
  2. The configuration is not flexible. If you need to add new protected resources, you need to manually add the init method to add flow control rules;

2.2  @ SentinelResource annotation implementation

  • Introduce dependencies
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel‐annotation‐aspectj</artifactId>
    <version>1.8.0</version>
</dependency>
  • Configuration aspect support
@Configuration
public class SentinelAspectConfiguration {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();  
    }
}
  • Write test logic, add @SentinelResource, configure blockHandler and fallback
@RequestMapping(value = "/findOrderByUserId/{id}")
@SentinelResource(
        value = "findOrderByUserId",
        fallback = "fallback",fallbackClass = ExceptionUtil.class,
        blockHandler = "handleException",blockHandlerClass = ExceptionUtil.class)
public R findOrderByUserId(@PathVariable("id") Integer id) {
    // ribbon实现
    String url = "http://mall ‐order/order/findOrderByUserId/"+id;
    R result = restTemplate.getForObject(url,R.class);
    if(id==4){
        throw new IllegalArgumentException("非法参数异常");
    }
    return result; 
}
  • Write ExceptionUtil (note: if a slave class is specified, the method must be static)
public class ExceptionUtil {                                                                                          
    public static R fallback(Integer id,Throwable e){
        return R.error( ‐2, "===被异常降级啦===");
    }

    public static R handleException(Integer id, BlockException e){
        return R.error( ‐2, "===被限流啦===");
    }                                                                                                                  	}
  • Flow control rule settings can be configured through Sentinel dashboard

        pom.xml: The client needs to introduce the Transport module to  communicate with the Sentinel console. 

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel‐transport‐simple‐http</artifactId>
    <version>1.8.0</version>
</dependency>

        application.yml: The client needs to configure  the Sentinel  console [IP: port] for communication.

Dcsp.sentinel.dashboard.server=consoleIp:port


3. Start the Sentinel console  

        Download the console jar  package and start it locally: you can refer to the official website documentation https://github.com/alibaba/Sentinel/releases

  • The console startup command of the jar package

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

        where  -Dserver.port=8080 is used to specify the Sentinel console port as  8080.

         From Sentinel 1.6.0 onwards, Sentinel console introduces basic login functionality, default username and password are both  sentinel. You can refer to  the authentication module documentation  to configure the username and password.

        Sentinel will  initialize when the client calls for the first time, and start sending heartbeat packets to the console, so make sure that the client has access.

  • View machine list and health status

        When you see your machine in the machine list, it means that you have successfully connected to the console; if you do not see your machine, please check the configuration and use the log to troubleshoot the cause. ${user.home}/logs/csp/sentinel-record.log.xxx 

  • Sentinel console


4. Spring Cloud Alibaba integrates Sentinel   

  • Introduce dependencies
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring‐cloud‐starter‐alibaba‐sentinel</artifactId>  
</dependency>
  •  Add yml configuration to set sentinel console address for microservices

        After adding Sentinel , you need to expose the / actuator / sentinel endpoint, and Springboot does not , so you need to set and test http :// localhost : 8800/actuator/sentinel 

server:
    port: 8800

spring:
    application:
    name: mall‐user‐sentinel‐demo
    cloud:
        nacos:
            discovery:
                server-addr: 127.0.0.1:8848
    sentinel:
        transport:
            # 添加sentinel的控制台地址
            dashboard: 127.0.0.1:8080
            # 指定应用与Sentinel控制台交互的端口,应用本地会起一个该端口占用的HttpServer
            # port: 8719
  • Set flow control rules sentinel console

  • Microservices and Sentinel  Dashboard Communication Principles

        A service discovery mechanism is implemented between the Sentinel console and the micro-server. The micro-services integrated with Sentinel will pass metadata to the Sentinel console  . The architecture diagram is as follows:


Guess you like

Origin blog.csdn.net/weixin_44259720/article/details/130677425