Spring Cloud Alibaba: Sentinel achieved with current-limiting fuse

SpringBoot actual electricity supplier item mall (20k + star) Address: github.com/macrozheng/...

Summary

Spring Cloud Alibaba is committed to providing one-stop solutions for micro-service development, Sentinel as one of its core components, has a range of services and limiting fuse protection, etc. This article will detail its usage.

About Sentinel

With the stability between the popular micro-services, services, and services is becoming increasingly important. Sentinel flow rate as a starting point, the flow rate control, fuse downgrade, a plurality of load protection systems dimension stability protection services.

Sentinel has the following characteristics:

  • Rich application scenarios: to undertake a nearly 10-year Alibaba's core scenario dual XI promote traffic spike for example, real-time application is unavailable blown downstream;
  • Complete real-time monitoring: while providing real-time monitoring. You can see a single machine-second data access applications in the console, or even a summary of the operation of the cluster size of 500 or less;
  • Wide open Ecology: providing the other open source framework / library integration module out of the box, for example, integration with Spring Cloud, Dubbo, gRPC of;
  • SPI perfect extension point: to provide easy to use, well-SPI extension points. You can achieve the expansion point, rapid custom logic.

Installation Sentinel Console

Sentinel console is a lightweight console application, it can be used to view real-time resource monitoring and stand-alone summary of cluster resources, and provides a series of rules of management functions such as flow control rules, demotion rules, rules hot spots.

  • We start with the official website to download Sentinel, here is the download sentinel-dashboard-1.6.3.jarfile, download address: github.com/alibaba/Sen...

  • After the download is complete, enter the following command at the command line to run the Sentinel console:

java -jar sentinel-dashboard-1.6.3.jar
复制代码
  • Sentinel console runs by default on port 8080, both logon account password sentinel, can be accessed via the following address: HTTP: // localhost: 8080

  • Sentinel console to view real-time monitoring of data on a single machine.

Create a sentinel-service module

Here we create a sentinel-service module for fusing and current limiting feature presentation of Sentinel.

  • Add in pom.xml its dependencies, here we use Nacos as a registry, we need to add dependent Nacos at the same time:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
复制代码
  • Add configuration in application.yml, primarily address Nacos and the Sentinel Console Configuration:
server:
  port: 8401
spring:
  application:
    name: sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
    sentinel:
      transport:
        dashboard: localhost:8080 #配置sentinel dashboard地址
        port: 8719
service-url:
  user-service: http://nacos-user-service
management:
  endpoints:
    web:
      exposure:
        include: '*'
复制代码

Limiting function

Sentinel Starter default for all HTTP services provide current limiting buried point, we can also customize the behavior of some limit by using @SentinelResource.

Creating RateLimitController class

Testing for fusing and current limiting.

/**
 * 限流功能
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /**
     * 按资源名称限流,需要指定限流处理逻辑
     */
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource() {
        return new CommonResult("按资源名称限流", 200);
    }

    /**
     * 按URL限流,有默认的限流处理逻辑
     */
    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl",blockHandler = "handleException")
    public CommonResult byUrl() {
        return new CommonResult("按url限流", 200);
    }

    public CommonResult handleException(BlockException exception){
        return new CommonResult(exception.getClass().getCanonicalName(),200);
    }

}
复制代码

According limiting resource name

We can limit the current operating according to value (resource name) @SentinelResource annotation defined, but need to specify limiting processing logic.

  • Flow control rules can be configured in the Sentinel console, because we use the Nacos registry, let's start Nacos and sentinel-service;

  • Because Sentinel uses lazy loading rules, we need to access the interface, Sentinel console will have a corresponding service information, we first visit at this interface: HTTP: // localhost: 8401 / ratelimit / byResource

  • Configuring flow control console Sentinel rules, value according to the value of annotation @SentinelResource:

  • Quick access to the top of the interface can be found to return the current limit their definition of information processing:

According to URL limiting

We can also limiting access through a URL, it will return to the default current limiting process information.

  • Configuring flow control rules Sentinel console, use access URL:

Custom processing logic flow restrictor

We can customize the generic limiting processing logic, and then specify the @SentinelResource.

  • CustomBlockHandler create custom class for limiting the processing logic:
/**
 * Created by macro on 2019/11/7.
 */
public class CustomBlockHandler {

    public CommonResult handleException(BlockException exception){
        return new CommonResult("自定义限流信息",200);
    }
}
复制代码
  • Limiting the use of a custom processing logic in the RateLimitController:
/**
 * 限流功能
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/rateLimit")
public class RateLimitController {

    /**
     * 自定义通用的限流处理逻辑
     */
    @GetMapping("/customBlockHandler")
    @SentinelResource(value = "customBlockHandler", blockHandler = "handleException",blockHandlerClass = CustomBlockHandler.class)
    public CommonResult blockHandler() {
        return new CommonResult("限流成功", 200);
    }

}
复制代码

Fuse function

Sentinel supports inter-service calls for protection, fault applications fusing operation, where we used to call interface RestTemplate nacos-user-service services provided to demonstrate this function.

  • First, we need to wrap @SentinelRestTemplate under RestTemplate instance:
/**
 * Created by macro on 2019/8/29.
 */
@Configuration
public class RibbonConfig {

    @Bean
    @SentinelRestTemplate
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}
复制代码
  • Add CircleBreakerController class, call interface provides definitions for nacos-user-service:
/**
 * 熔断功能
 * Created by macro on 2019/11/7.
 */
@RestController
@RequestMapping("/breaker")
public class CircleBreakerController {

    private Logger LOGGER = LoggerFactory.getLogger(CircleBreakerController.class);
    @Autowired
    private RestTemplate restTemplate;
    @Value("${service-url.user-service}")
    private String userServiceUrl;

    @RequestMapping("/fallback/{id}")
    @SentinelResource(value = "fallback",fallback = "handleFallback")
    public CommonResult fallback(@PathVariable Long id) {
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    @RequestMapping("/fallbackException/{id}")
    @SentinelResource(value = "fallbackException",fallback = "handleFallback2", exceptionsToIgnore = {NullPointerException.class})
    public CommonResult fallbackException(@PathVariable Long id) {
        if (id == 1) {
            throw new IndexOutOfBoundsException();
        } else if (id == 2) {
            throw new NullPointerException();
        }
        return restTemplate.getForObject(userServiceUrl + "/user/{1}", CommonResult.class, id);
    }

    public CommonResult handleFallback(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服务降级返回",200);
    }

    public CommonResult handleFallback2(@PathVariable Long id, Throwable e) {
        LOGGER.error("handleFallback2 id:{},throwable class:{}", id, e.getClass());
        User defaultUser = new User(-2L, "defaultUser2", "123456");
        return new CommonResult<>(defaultUser,"服务降级返回",200);
    }
}
复制代码
  • Start nacos-user-service and sentinel-service service:

  • Since we did not define a user id of 4 in nacos-user-service, all access to the following interfaces will return to service degradation results: HTTP: // localhost: 8401 / Breaker / fallback / 4

{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "服务降级返回",
	"code": 200
}
复制代码

Used in conjunction with Feign

Sentinel also fit the Feign components, we use Feign to time between service calls, you can also use it to blow.

  • First, we need to add Feign its dependencies in pom.xml:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
复制代码
  • Sentinel open support for Feign in application.yml in:
feign:
  sentinel:
    enabled: true #打开sentinel对feign的支持
复制代码
  • Add in the application startup class @EnableFeignClients start Feign function;

  • Create a UserService interface that defines the call to nacos-user-service services:

/**
 * Created by macro on 2019/9/5.
 */
@FeignClient(value = "nacos-user-service",fallback = UserFallbackService.class)
public interface UserService {
    @PostMapping("/user/create")
    CommonResult create(@RequestBody User user);

    @GetMapping("/user/{id}")
    CommonResult<User> getUser(@PathVariable Long id);

    @GetMapping("/user/getByUsername")
    CommonResult<User> getByUsername(@RequestParam String username);

    @PostMapping("/user/update")
    CommonResult update(@RequestBody User user);

    @PostMapping("/user/delete/{id}")
    CommonResult delete(@PathVariable Long id);
}
复制代码
  • UserService create UserFallbackService class implements an interface, logic for handling service degradation:
/**
 * Created by macro on 2019/9/5.
 */
@Component
public class UserFallbackService implements UserService {
    @Override
    public CommonResult create(User user) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服务降级返回",200);
    }

    @Override
    public CommonResult<User> getUser(Long id) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服务降级返回",200);
    }

    @Override
    public CommonResult<User> getByUsername(String username) {
        User defaultUser = new User(-1L, "defaultUser", "123456");
        return new CommonResult<>(defaultUser,"服务降级返回",200);
    }

    @Override
    public CommonResult update(User user) {
        return new CommonResult("调用失败,服务被降级",500);
    }

    @Override
    public CommonResult delete(Long id) {
        return new CommonResult("调用失败,服务被降级",500);
    }
}
复制代码
  • Use UserService in UserFeignController call nacos-user-service service interfaces Feign:
/**
 * Created by macro on 2019/8/29.
 */
@RestController
@RequestMapping("/user")
public class UserFeignController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public CommonResult getUser(@PathVariable Long id) {
        return userService.getUser(id);
    }

    @GetMapping("/getByUsername")
    public CommonResult getByUsername(@RequestParam String username) {
        return userService.getByUsername(username);
    }

    @PostMapping("/create")
    public CommonResult create(@RequestBody User user) {
        return userService.create(user);
    }

    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        return userService.update(user);
    }

    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id) {
        return userService.delete(id);
    }
}
复制代码
{
	"data": {
		"id": -1,
		"username": "defaultUser",
		"password": "123456"
	},
	"message": "服务降级返回",
	"code": 200
}
复制代码

Use Nacos storage rules

By default, when we configure rules in the Sentinel console, the console push rule is through the API rules to the clients and updates directly into memory. Once we restart the application, the rule will disappear. Here we describe how to configure the next rule for persistence to store the Nacos example.

Schematic

  • First we create rules directly in the distribution center, distribution center will rule pushed to the client;

  • Sentinel console also to obtain configuration information from the configuration center.

Demo

  • First add its dependencies in pom.xml:
<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
复制代码
  • Application.yml modify the configuration file, add Nacos data source configuration:
spring:
  cloud:
    sentinel:
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-sentinel
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow
复制代码
  • In Nacos add configuration:

  • Add the configuration information is as follows:
[
    {
        "resource": "/rateLimit/byUrl",
        "limitApp": "default",
        "grade": 1,
        "count": 1,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]
复制代码
  • Interpretation of the relevant parameters:

    • resource: The resource name;
    • limitApp: Source application;
    • grade: threshold type, the number of threads represents 0, 1 represents QPS;
    • count: single threshold value;
    • strategy: flow-control mode, directly represents 0, 1 represents association, 2 denotes a link;
    • controlBehavior: effect of fluidics, represents fast failure 0, 1 represents a Warm Up, 2 denotes waiting;
    • clusterMode: whether the cluster.
  • Sentinel console have found the following limiting rules:

  • Quick access to test interface can be found to return the limiting process information:

Reference material

Spring Cloud Alibaba official document: github.com/alibaba/spr...

To use the module

springcloud-learning
├── nacos-user-service -- 注册到nacos的提供User对象CRUD接口的服务
└── sentinel-service -- sentinel功能测试服务
复制代码

Project Source Address

github.com/macrozheng/…

No public

mall project a full tutorial serialized in public concern number the first time to obtain.

No public picture

Guess you like

Origin juejin.im/post/5dd29bece51d4561e80f9053