SpringCloud (four) Hystrix fuse

As already learned registration and service discovery component, load balancing component, so that our micro-services system is ready for use. In order to ensure availability, single service often cluster deployment. As the network reasons or for their own reasons, the service does not guarantee 100% available, if a single service issue arise, to call this service will be thread is blocked, at this time if the influx of a large number of requests, Servletthe thread container resources will be consumed completed, resulting in paralysis of service. Dependencies between services and service failures will spread, will service the entire micro system have serious consequences disastrous, this is the fault of service "avalanche" effect.

This allows the need for isolation and management failures and delay, so that a single failure of dependent relationship, you can not cancel the entire application or system.

To solve this problem, the industry made fuse model.

Hystrix is ​​a distributed system for processing delays and fault-tolerant open source libraries, distributed systems, many rely inevitably call fails, such as overtime, abnormal, Hystrix can guarantee in the case of a dependency problem, It will not result in an overall service to fail, to avoid cascading failures, in order to improve the flexibility of distributed systems.

"Breaker" is a switching apparatus itself, when a service unit fails, the fault monitoring circuit breaker (similar to a blown fuse), and returns to the caller a line with expectations, the response may be processed alternatively (FallBack) instead of waiting for a long time or throw an exception caller can not handle, thus ensuring the caller to the service thread it will not be long, unnecessarily occupied, so as to avoid the spread of the fault in the distributed system, and even avalanche.

This component is well understood, is to ensure the availability of services, and the failure of some services with care to prevent the entire service will hang.

A, Ribbon fuses used

There are two ways to service the caller Ribbon and Feign, now use the Ribbon, on the first project

Add dependent

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

Increase in the Application Notes in @EnableHystrix

@EnableDiscoveryClient
@SpringBootApplication
@EnableHystrix
public class ConsumerDeptRibbonApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerDeptRibbonApplication.class, args);
    }
}

Increase in @HystrixCommand annotations Service

Add method on the need for fusing mechanism of @HystrixCommand , property fallbackMethod is returned when fusing method:

@Service
public class DeptService {
    @Autowired
    private RestTemplate restTemplate;

    @HystrixCommand(fallbackMethod = "hiError")
    public String sayHi(String message) {
        //这里指指定了服务名称,不用管ip 地址与端口
        return restTemplate.getForObject("http://SPRING-CLOUD-LEARN-PROVIDER-DEPT/hi?message=" + message, String.class);
    }

    public String hiError(String message) {
        return "Hi,your message is :\"" + message + "\" but request error.";
    }
}

This development has been completed, we make the appropriate test

Start spring-cloud-learn-eureka registry, start sector service providers spring-cloud-learn-provider- dept, and then start the spring-cloud-learn-consumer- dept-ribbon, this time the service properly, we can get the normal feedback, the same as before, then we stopped spring-cloud-learn-provider- dept, then refresh the HTTP: // localhost: 8764 / hi the Message = the Hello? , will find:

Two, Feign use fuses

Feign is built fuse, but is off by default. You need to configure to open it in the configuration file, add the following code to the configuration file:

feign:
  hystrix:
    enabled: true

Then we create a class that specifically address fuse associated with the corresponding services:

@Component
public class DeptServiceHystrix implements DeptService {

    @Override
    public String sayHi(String message) {
        return "Hi,your message is :\"" + message + "\" but request error.";
    }
}

This class inherits DeptService, then implement feedback services provided should appear when the fuse, and then add in the original service fallback specified class

//服务提供者的名字
@FeignClient(value = "spring-cloud-learn-provider-dept", fallback = DeptServiceHystrix.class)
public interface DeptService {

    @RequestMapping(value = "hi", method = RequestMethod.GET)
    String sayHi(@RequestParam(value = "message") String message);
}

Then start the spring-cloud-learn-consumer-dept-feign, after the service sector hang up, the effect can be achieved fuse

There is also a way to create a factory, a new DeptServiceFallbackFactory:

@Component
public class DeptServiceFallbackFactory implements FallbackFactory<DeptService> {
    @Override
    public DeptService create(Throwable throwable) {
        return new DeptService() {
            @Override
            public String sayHi(String message) {
                return "Hi,your message is :\"" + message + "\" but request error.";
            }
        };
    }
}

Third, the fuse monitoring dashboard

In addition to calling isolation dependent services, Hystrix also provides near real-time call monitoring (Hystrix Dashboard), Hystrix will continue to record execution information for all by Hystrix initiated the request, and presented to the user in the form of statistical reports and graphs, including how many successful execution of the request number, the number of failures per second and so on. Netflix realized the monitoring of these indicators by hystrix-metrics-event-stream projects. Spring Cloud also provides integrated Hystrix Dashboard, and monitoring content into visual interface.

Increase Hystrix dashboard features in Ribbon and Feign project, the same way the transformation of two projects:

Dependent increase in pom.xml

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

Increase in the Application Notes in @EnableHystrixDashboard

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

Creating the Servlet configuration hystrix.stream

Spring Boot 2.x version is slightly different turn Hystrix Dashboard and Spring Boot 1.x way, need to add a HystrixMetricsStreamServlet configuration code is as follows:

@Configuration
public class HystrixDashboardConfiguration {
    @Bean
    public ServletRegistrationBean getServlet() {
        HystrixMetricsStreamServlet streamServlet = new HystrixMetricsStreamServlet();
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(streamServlet);
        registrationBean.setLoadOnStartup(1);
        registrationBean.addUrlMappings("/hystrix.stream");
        registrationBean.setName("HystrixMetricsStreamServlet");
        return registrationBean;
    }
}

Then start the project, open Address: HTTP: // localhost: 8765 / hystrix , here you can see the dashboard successful start

1: Delay: This parameter is used to control the delay time of polling monitoring information on the server, the default is 2000 ms, the client can be reduced by configuring the properties of the network and CPU consumption.

2: Title: This parameter corresponds to the content of the head after the title Hystrix Stream, the default URL will be used to monitor specific instances, may be a more appropriate title by showing the configuration information.

click to enter:

This time there is no data, data looked at to learn how we can refresh before calling service interface

 

Rainbow: according to the results showed various colors

Filled circles: There are two meanings. It represents the health of the instance by changing the color of its health decreases from green <yellow <Orange <red. The solid circles in addition change in color, its size changes depending on the request flow example, the greater the flow rate the greater the solid circles. So by showing the solid circles, you can quickly find plenty of examples of the failed instance and instance of high pressure.

Curve: for a relative change in flow rate within 2 minutes of recording, the observed increase in the flow through and decreased it.

The practice under their own is better understood.

Guess you like

Origin www.cnblogs.com/yuanqinnan/p/11546029.html