Spring Cloud core components - blown downgrade

First is that today "service fuse" and "service degradation."

Services fuse : everyone is familiar with the stock market, the fuse of the word, means that when the volatility of the stock reaches a certain point, the exchange suspended trading for the measures taken to control risks. Accordingly, the service fuse generally refers to a software system, for some reason makes the service appeared overload, to prevent total system failure, in order to adopt a protective measure, so many places to fuse also known as overload protection.

Service degradation : We've all seen the girls travel it, oversized luggage is an essential matter, usually more than enough to walk near, but once out of a far door, and then a big box are no good, and how to do it? Common scenario is to put items out sub-sub-heap, the ratio off than the last number of non-essentials to reluctantly put down, wait until the next box is good enough, then put with a use. The service degradation, is such a thing, the overall resources fast enough, some reluctantly turn off the service, to be ride out the storm, and then turn back.

So from the above analysis point of view, there is actually from some point of view there is a certain similarity:

1) Objective very consistent , it is offered from the reliable availability of the overall system in order to prevent collapse or even slow, the technical means employed;

2) The final performance is similar for both, the end-user experience to make is that some features are temporarily unreachable or unavailable;

3) size are generally level of service , of course, the industry also has a lot more fine-grained approach, such as data persistence layer to do (allow the query does not allow additions and deletions);

4) high autonomy requirements , fuse mode are generally based service automatically trigger policy may downgrade although human intervention, but in the micro-service architecture, relies entirely on the apparently impossible, switch preset configuration center are all necessary means ;

The difference between the two is obvious:

1) Trigger the reasons are not the same , service is typically a service fuse (downstream services) failure caused, the service is generally degraded from the viewpoint of the entire load;

2) level management objectives are not the same , in fact, is a framework for fusing level processing, services are required for each micro (no sub-levels of), while downgrading the general level of the need to have divided the business (such as is usually downgrade from the outermost services start)

3) implementation are not the same

Reference article: https://blog.csdn.net/guwei9111986/article/details/51649240

 

Here Hystrix:

In a distributed environment, many service dependencies some is bound to fail. Hystrix is ​​a library by adding delay tolerant and fault-tolerant logic to help you control the interaction between these distributed services. Hystrix through an access point between the quarantine service, stop cascading failures and provide fallback options to achieve this, all of which can increase the overall resilience of the system.

Hystrix provides a fuse, isolation, Fallback, Cache, monitoring and other functions. After the error message can fallback error handling, returns some data reveal all the details and so on.

https://www.cnblogs.com/cjsblog/p/9391819.html

 

Examples of this undertaking in the previous article: https://www.cnblogs.com/jwen1994/p/11408511.html

1. Feign combination of Breaker Hystrix

The first step: Add dependence

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

Note that the old and new version of the problem, so to give priority to the official website, or part of the notes will be lost

Step Two: Start class notes which increase @EnableCircuitBreaker

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class OrderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

We can also use SpringCloudApplication notes, it contains a lot Spring Cloud-related notes

The third step: Use the outermost api

Increase @HystrixCommand (fallbackMethod = "saveOrderFail") on api method. Like exception handling (exception parameters or internal call network problems)

@RestController
@RequestMapping("api/v1/order")
public class OrderController {

    @Autowired
    private ProductOrderService productOrderService;

    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId){

        Map<String, Object> data = new HashMap<>();
        data.put("code", 0);
        data.put("data", ProductOrderService.save (the userId, the productId));
         return   Data; 
    } 

    // Note that the method signatures must be consistent with the method and api 
    Private Object saveOrderFail (the userId int, int the productId) { 
        the Map <String, Object> MSG = new new the HashMap < > (); 
        msg.put ( "code", -1 ); 
        msg.put ( "msg", "number of people buying too much, you squeezed out, wait a retry" );
         return msg; 
    } 
}

Note: Write fallback method implementation, the method signature must be consistent and api method signature

The fourth step: testing, we used a request to be wrong, it will return saveOrderFail return value

 

2. When you call our service, if the service error, we would like to do some processing

 The first step: Turn Feign support Hystrix (attention must be turned on by default to support the old version, the new version off by default)

feign:
  hystrix:
    enabled: true

Step two: FeignClient (name = "xxx", fallback = xxx.class), class needs to inherit the current class FeignClient

@FeignClient(name = "product-service", fallback = ProductClientFallback.class)
public interface ProductClient {
    @GetMapping("/api/v1/product/find")
    String findById(@RequestParam(value = "id") int id);
}

ProductClientFallback class

@Component
public class ProductClientFallback implements ProductClient {
    @Override
    public String findById(int id) {
        System.out.println("feign 调用product-service findbyid 异常");
        return null;
    }
}

 

3. To further improve the abnormal alarm notification

We can try to achieve a Redis join abnormal alarm

The first step: Add rely Redis

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

Step Two: Configure link information Redis

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    timeout: 2000

The third step: modifying code

@RestController
@RequestMapping("api/v1/order")
public class OrderController {
    @Autowired
    private ProductOrderService productOrderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("save")
    @HystrixCommand(fallbackMethod = "saveOrderFail")
    public Object save(@RequestParam("user_id")int userId, @RequestParam("product_id") int productId, HttpServletRequest request){

        Map<String, Object> data = new HashMap<>();
        data.put ( "code", 0 ); 
        data.put ( "Data" , productOrderService.save (the userId, the productId));
         return   Data; 
    } 

    // Note that the method signatures must be consistent with the method and api 
    Private Object saveOrderFail ( int the userId, int the productId, the HttpServletRequest Request) {
         // monitoring alarm 
        String saveOrderKye = "Save-Order" ; 

        String sendValue = redisTemplate.opsForValue () GET (saveOrderKye);.
         Final String IP = request.getRemoteAddr ();
         new new the Thread ( () -> {
            IF (StringUtils.isBlank (sendValue)) { 
                System.out.println ( "urgent message, the user single failure, please find out the reasons to leave, ip address =" + ip);
                 // send a http request, call the SMS service TODO 
                redisTemplate.opsForValue () SET (saveOrderKye, "Fail-Save-Order", 20 is. , TimeUnit.SECONDS); 

            } the else { 
                System.out.println ( "has sent a message, the transmission will not be repeated within 20 seconds" ); 
            } 

        .}) Start (); 

        the Map <String, Object> MSG = new new the HashMap <> (); 
        msg.put ( "code", -1 ); 
        msg.put ( "MSG", "The number of buy too much, you squeezed out, wait a retry " );
        return msg;
    }
}

 

4. Hystrix downgrade policies and adjustment

1) Review the default policy to explain HystrixCommandProperties

This file can see all the default policy

2) execution.isolation.strategy isolation strategy

Hystrix There are two isolation strategy: THREAD thread pool isolation (default), SEMAPHORE Semaphore. Semaphore interfaces for high concurrency situations, as in the case of thousands of calls per second, resulting in high overhead of thread, usually only apply to non-network calls, fast execution speed

3) execution.isolation.thread.timeoutInMilliseconds timeout

Hystrix default timeout is 1000 ms

4) execution.timeout.enabled whether to open the timeout limit (must not be disabled)

Hystrix is ​​enabled by default timeout limit

5) execution.isolation.semaphore.maxConcurrentRequests isolation strategy semaphore time, if the maximum number of concurrent, subsequent requests will be rejected, the default is 10

# Disable the timeout hystrix 
#hystrix: 
# Command: 
# default: 
# Execution: 
# timeout: 
# Enabled: to false 

# = 4000 execution.isolation.thread.timeoutInMilliseconds 

# Set timeout 
hystrix: 
  Command: 
    default: 
      Execution: 
        Isolation: 
          Thread : 
            timeoutInMilliseconds: 4000

The official document: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.strategy

The circuit breaker monitoring dashboard Dashboard

Almost no production environment, as long as you can make an exception alert

The first step: Add dependence

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

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

Step Two: Start class adds annotation @EnableHystrixDashboard

The third step: to increase the profile endpoint

# Expose all of the monitoring information 
Management: 
  Endpoints: 
    Web: 
      Exposure: 
        the include: "*"

Step four: access entry

1) Access: HTTP: // localhost: 8781 / hystrix

2)Hystrix Dashboard 输入: http://localhost:8781/actuator/hystrix.stream

Reference: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-security-actuator

 

 

NOTE: If you download from the Maven central warehouse is too slow, but modify the Maven repository address, other Maven repository. In order to use Ali cloud storage, we modify the pom.xml

<repositories>
  <repository>
    <id>nexus-aliyun</id>
    <name>Nexus aliyun</name>
    <layout>default</layout>
    <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    <snapshots>
      <enabled>false</enabled>
    </snapshots>
    <releases>
      <enabled>true</enabled>
    </releases>
  </repository>
</repositories>

 

Guess you like

Origin www.cnblogs.com/jwen1994/p/11432842.html