SpringCloud study notes (4): Hystrix fault tolerance

Brief introduction

In the micro-service architecture, service dependencies between micro complex, some services will inevitably fail, leading to service the caller appears remote thread to block scheduling. At high load scenario, if no treatment, may cause cascading failures, leading to the depletion of resources caller to the service or even the entire system Ben collapse. Hystrix Netflix is ​​a delay of a fault-tolerant and open-source libraries, which help to control the interaction between these micro-services by adding delay tolerant and fault-tolerant logic. Hystrix through an access point between the isolation Services, stop the cascading failures across services and to provide fallback options to achieve this, all of these options to improve the overall resilience of the system.

Project Introduction

  1. sc-parent, parent module (please refer SpringCloud Study Notes (1): Eureka registry )
  2. sc-eureka, Registration Center (refer to SpringCloud Study Notes (1): Eureka registry )
  3. sc-provider, the provider (refer to SpringCloud Study Notes (1): Eureka registry )
  4. sc-consumer-hystrix-ribbon, consumers use Hystrix + Ribbon
  5. sc-consumer-hystrix-feign, using Hystrix + Feign consumers

Use Hystrix on the Ribbon

1. Create a sub-module project sc-consumer-hystrix-ribbon under the parent module, pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.cf</groupId>
    <artifactId>sc-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>sc-consumer-hystrix-ribbon</artifactId>
  
  <dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
  </dependencies>
</project>

2. Create a startup class consumer.ConsumerApplication:

package consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableCircuitBreaker
public class ConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
    
    //为RestTemplate整合Ribbon,使其具备负载均衡的能力
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

3. Create a call to service providers Controller: consumer.controller.ConsumerController

package consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

@RestController
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;
    
    @HystrixCommand(fallbackMethod="getBookListFallBack")
    @GetMapping("/getBookList")
    public String getBookList(){
        return restTemplate.getForObject("http://sc-provider/book/list", String.class);
    }
    
    public String getBookListFallBack(){
        return "[\"Java入门到放弃\"]";
    }
}

@HystrixCommand : representation will getBookList method as hystrix command call.
fallbackMethod : fallback method specified processing logic, here is getBookListFallBack method, when getBookList ran abnormal method will be called getBookListFallBack method.
Note: fallback method should be called as a method hystrix commands have the same signature.

4. Create application.yml:

server:
  port: 8083

spring:
  application:
    name: sc-consumer-hystrix-ribbon
    
eureka:
  client:
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://localhost:8080/eureka/    

5. Test

In turn starts registry sc-eureka, provider sc-provider, consumers sc-consumer-hystrix-ribbon, and visit http: // localhost: 8083 / getBookList, results are shown below:

This is the value provider returns normally, the next will be provided by sc-provider shut down, once again visit http: // localhost: 8083 / getBookList, results are shown below:

Because after the provider sc-provider shut down, consumers will complain and then access provider, Hystrix capture calls the rollback method directly after the exception is getBookListFallBack method.

Use Hystrix on Feign

1. Create a sub-module project sc-consumer-hystrix-feign under the parent module, pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.cf</groupId>
    <artifactId>sc-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  </parent>
  <artifactId>sc-consumer-hystrix-feign</artifactId>
  
  <dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
  </dependencies>
</project>

2. Create a startup class feign.FeignApplication:

package feign;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
public class FeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FeignApplication.class, args);
    }
}

3. Create Feign declarative interfaces: feign.inter.BookService

package feign.inter;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

import feign.fallback.BookFallBack;

@FeignClient(value="sc-provider", fallbackFactory=BookFallBack.class)
public interface BookService {
    
    @GetMapping("/book/list")
    public String getBookList();
}

fallbackFactory property @FeignClient annotation is specified Feign client interface defined fallback factory.

4. Create a call to service providers Controller:

package feign.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import feign.inter.BookService;

@RequestMapping("/feign")
@RestController
public class FeignController {
    @Autowired
    private BookService bookService;
    
    @GetMapping("/getBookList")
    public String getBookList(){
        return bookService.getBookList();
    }
}

5. Create application.yml:

server:
  port: 8084

spring:
  application:
    name: sc-consumer-hystrix-feign

eureka:
  client:
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://localhost:8080/eureka/   

feign:
  hystrix:
    enabled: true  #开启hystrix支持     

6. Create a rollback factory class:

package feign.fallback;
import org.springframework.stereotype.Component;

import feign.hystrix.FallbackFactory;
import feign.inter.BookService;

@Component
public class BookFallBack implements FallbackFactory<BookService>{
    @Override
    public BookService create(Throwable cause) {
        return new BookService() {
            @Override
            public String getBookList() {
                return "[\"Java入门到放弃\"]";
            }
        };
    }
}

create method returns an instance of rollback, rollback examples Feign statement BookService interface implementation class, providing a fallback method and corresponding BookService, will call the rollback method to achieve class when BookService interface call failed.

7. Test:

In turn starts registry sc-eureka, provider sc-provider, consumers sc-consumer-hystrix-feign, and visit http: // localhost: 8084 / feign / getBookList, results are shown below:

This is the value provider returns normally, the next will be provided by sc-provider shut down, once again visit http: // localhost: 8084 / feign / getBookList, results are shown below:

8. Review the reason rollback

Modify the fallback factory class BookFallBack:

@Component
public class BookFallBack implements FallbackFactory<BookService>{
    @Override
    public BookService create(Throwable cause) {
        return new BookService() {
            @Override
            public String getBookList() {
                //将回退原因输出到控制台
                cause.printStackTrace(System.out);
                return "[\"Java入门到放弃\"]";
            }
        };
    }
}

In turn starts registry sc-eureka, consumers sc-consumer-hystrix-feign, and visit http: // localhost: 8084 / feign / getBookList, console output:

com.netflix.hystrix.exception.HystrixTimeoutException
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1142)
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41)
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37)
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57)
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1159)
        ......

Guess you like

Origin www.cnblogs.com/seve/p/11535891.html
Recommended