Moment For Technology

Learn SpringCloud Hystrix to take you from 0 to 1

Posted on Sept. 23, 2022, 9:48 a.m. by Lisa Tran
Category: The back-end Tag: java

What is a catastrophic avalanche effect

1. The process of avalanches

Normally the request passes through multiple services to service T, which processes it and returns it step by step.

When service B receives a large number of requests, service T, which ultimately processes the service, becomes stressed, causing the service to crash.

Because service T goes down first, requests pile up at service U, and all levels of the system collapse when the pressure gets too high, rendering service on that line completely unusable.

The failure of one line affects the others, and the whole system collapses

2. Causes of avalanches

  • Service provider unavailable (hardware failure, program bug, cache breakdown, large number of user requests)
  • Retry Increases traffic (user retry, code logic retry)
  • Service caller unavailable (resource depletion due to synchronous waiting)

The end result is that one service becomes unavailable, and multiple services become unavailable, leading to a total system breakdown.

How to solve the catastrophic avalanche effect

  • demotion

    Demotion due to timeout or insufficient resources (thread or semaphore), after demotion can be used with the demotion interface to return the bottom data.

    Implement a fallback method that can be used to return a value when an exception occurs on the request back-end service.

  • Isolation (thread pool isolation and semaphore isolation)

    Restrict the use of resources for invoking distributed services, so that problems in one service invocation do not affect other service invocations.

  • fusing

    When the failure rate (the failure rate caused by network faults or timeout) reaches the threshold, the fault is degraded automatically. The quick failure triggered by fuses is quickly recovered

  • The cache

    Request caching is provided

  • Request to merge

    Provide request merge

1. The drop

Degrade the service

1.1 Creating a Project
1.2 Adding Coordinates
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency
Copy the code
1.3 Modifying the Configuration File
Name =eureka-consumer-ribbon-hystrix server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
1.4 Modifying startup classes to enable fuses
// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
1.5 Add the Product entity class to the project
1.6 modify ProductService
@Service
public class ProductService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;  //ribbon: load balancer

    // Enable service degradation processing and specify the method to return the bottom data
    @HystrixCommand(fallbackMethod = "fallback")
    public ListProduct getUsers(a){

        // Select the name of the service to invoke
            //ServiceInstance: encapsulates basic service information, such as the IP address and port number
        ServiceInstance si = loadBalancerClient.choose("ego-product-provider");
        // Concatenate the URL to access the service
        StringBuffer sb = new StringBuffer();

        //http://localhost:9001/user/product/findAll
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/product/findAll");
        System.out.println(sb.toString());
        //SpringMVC RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReferenceListProduct type = new ParameterizedTypeReferenceListProduct() {
        };

        //ResponseEntity: encapsulates the return value information
        ResponseEntityListProduct entity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, type);
        return entity.getBody();
    }

    // The method that returns the base data
    public ListProduct fallback(a){
        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        returnlist; }}Copy the code
1.7 The getFallback call is triggered in the following four cases
  • Method to throw a non HystrixBadRequestException anomalies
  • Method call timeout
  • The fuse turns on the interception call
  • Whether the thread pool queue semaphore is full

2. Request cache

In order to reduce the frequency of accessing services, Hystrix supports caching of a request and the returned result. If the URL is not changed, Hystrix directly returns the result from the cache instead of requesting the service. In this way, the service access pressure is greatly reduced.

Hystrix comes with a cache, which has two drawbacks

1. It is a local cache, which is synchronized in the cluster case.

2. Third-party cache containers are not supported. For example, Redis and Memcache

Solution: You can use Spring's cache

2.1 installation Redis
2.2 Creating a Project
2.3 Adding Coordinates
dependency
    groupIdorg.springframework.boot/groupId
    artifactIdspring-boot-starter-data-redis/artifactId
/dependency
Copy the code
2.4 Modifying the Configuration File
Name =eureka-consumer-ribbon-cache server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ Redis. host=192.168.234.129 # redis.port=6379 # Redis. port=6379 Spring.redis.pool. max-active=100 # Max wait time Spring.redis.pool. max-wait=3000 # Max wait time spring.redis.pool.max-idle=200 # minimum number of idle connections spring. Redis. Pool. Min - idle = 50 # connection timeout spring. Redis. Pool. Timeout = 600Copy the code
2.5 Modifying startup Classes to enable caching
@EnableCaching
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
2.6 modify ProductService
@Service
// Set a uniform prefix for cached data
@CacheConfig(cacheNames = {"com.luyi.ego.product"})
public class ProductService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;  //ribbon: load balancer

    // Enable service degradation processing and specify the method to return the bottom data
    @HystrixCommand(fallbackMethod = "fallback")
    public ListProduct getUsers(a){

        // Select the name of the service to invoke
            //ServiceInstance: encapsulates basic service information, such as the IP address and port number
        ServiceInstance si = loadBalancerClient.choose("ego-product-provider");
        // Concatenate the URL to access the service
        StringBuffer sb = new StringBuffer();

        //http://localhost:9001/user/product/findAll
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/product/findAll");
        System.out.println(sb.toString());
        //SpringMVC RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReferenceListProduct type = new ParameterizedTypeReferenceListProduct() {
        };

        //ResponseEntity: encapsulates the return value information
        ResponseEntityListProduct entity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, type);
        return entity.getBody();
    }

    // The method that returns the base data
    public ListProduct fallback(a){
        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        return list;
    }

    // Query goods by id
    @Cacheable(key = "'product' + #id")  // Add a key for the suffix id
    public Product getProductById(Integer id){
        System.out.println("============Get===========" + id);
        return new Product(id, "New merchandise");
    }

    // Delete goods by id
    @CacheEvict(key = "'product' + #id")
    public void delProductById(Integer id){
        System.out.println("============Del==========="+ id); }}Copy the code
2.7 modify the ProductController
@RestController
public class ProductController {

    @Autowired
    private ProductService userService;

    @RequestMapping("/consumer")
    public ListProduct getUsers(a){
        return userService.getUsers();
    }

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public Product get(Integer id){
        return userService.getProductById(id);
    }

    @RequestMapping(value = "del", method = RequestMethod.GET)
    public void del(Integer id){ userService.delProductById(id); }}Copy the code

3. Request a merge

3.1 Unmerged requests and merged requests

3.2 When is request merge used

In the microservice architecture, it is divided into several small modules, which need to communicate when calling each module. However, in the case of large concurrency, a large number of threads will be in the waiting state, which will increase the response time. Therefore, multiple requests can be combined into one request by using request merge.

3.3 Disadvantages of requesting merge

After setting up the request merge, it would have taken 5ms to complete a request, but with the request merge, it might have to wait another 10ms to see if there are any other requests, which increases the request from 5ms to 15ms. However, if the command we are issuing is already a high-latency command, then request merge can be used at this point, because the time consumption of the time window becomes insignificant. High concurrency is also an important scenario for merging requests.

3.4 Creating a Project
3.5 Modifying the POM File, add the Hystrix coordinates
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency

Copy the code
3.6 Modifying a Configuration File
Name =eureka-consumer-ribbon- Batch server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
3.7 modify ProductService
@Service
public class ProductService {

    // Use Hystrix to merge requests
    @HystrixCollapser(batchMethod = "batchProduct", scope =
            com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
            collapserProperties = {
                    // requests with an interval of less than 20ms are consolidated into one request. The default is 10ms
                    @HystrixProperty(name =
                            "timerDelayInMilliseconds", value = "20"),
                    // Sets the maximum number of requests allowed in a batch before triggering execution.
                    @HystrixProperty(name = "maxRequestsInBatch",
                            value = "200"})),// The method called by the Consumer Controller, which must return a value of type Future
    public FutureProduct getProduct(Integer id) {
        System.out.println("= = = = = = = = = = = = = =" + id + "= = = = = = = = = = = =");
        return null;
    }

    // Call the Provider service method (assumed)
    @HystrixCommand
    public ListProduct batchProduct(ListInteger ids) {
        for (Integer id : ids) {
            System.out.println(id);
        }
        // Suppose it is the list returned after calling the provider service
        ListProduct list = new ArrayList();
        list.add(new Product(1."Television"));
        list.add(new Product(2."Computer"));
        list.add(new Product(3."Refrigerator"));
        list.add(new Product(4."Flashlight"));
        list.add(new Product(100."list....."));
        System.out.println("ddddddddddd");
        returnlist; }}Copy the code
3.8 modify the Controller
@RestController
public class ProductController {

    @Autowired
    private ProductService userService;

    @RequestMapping("/consumer")
    public void getUsers(a) throws ExecutionException, InterruptedException {
        FutureProduct p1 = userService.getProduct(1);
        FutureProduct p2 = userService.getProduct(2);
        FutureProduct p3 = userService.getProduct(3); System.out.println(p1.get().toString()); System.out.println(p2.get().toString()); System.out.println(p3.get().toString()); }}Copy the code
3.9 Request Merge Parameters

4. Service fuse

4.1 Creating a Project
4.2 Adding Hystrix Coordinates
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency

Copy the code
4.3 Modifying the Configuration File
Name =eureka-consumer-ribbon-breaker server. Port =9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
4.4 Modifying a Startup Class
// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
4.5 modify ProductService
@Service
public class ProductService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;  //ribbon: load balancer

    @HystrixCommand(fallbackMethod = "fallback",
            commandProperties = {
                    // Default 20; When the number of requests exceeds 20 within 10 seconds, the fuse is started. When the request meets the fuse condition, getFallback() is triggered.
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,
                            value = "10"),
                    // The request is fusing when the request error rate is greater than 50%. The for loop then initiates the request and gets getFallback() when the request meets the fusing condition.
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,
                            value = "50"),
                    // Default 5 seconds; Fuse how many seconds before you try the request
                    @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,
                            value = "5000"})),public ListProduct getUsers(Integer flag) {
        System.out.println(flag);
        if (flag == 1) {throw new RuntimeException();
        }

        // Select the name of the service to invoke
        //ServiceInstance: encapsulates basic service information, such as the IP address and port number
        ServiceInstance si = loadBalancerClient.choose("ego-product-provider");
        // Concatenate the URL to access the service
        StringBuffer sb = new StringBuffer();

        //http://localhost:9001/user/product/findAll
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/product/findAll");
        System.out.println(sb.toString());
        //SpringMVC RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReferenceListProduct type = new ParameterizedTypeReferenceListProduct() {
        };

        //ResponseEntity: encapsulates the return value information
        ResponseEntityListProduct entity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, type);
        return entity.getBody();
    }

    // The method that returns the base data
    public ListProduct fallback(Integer flag) {
        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        returnlist; }}Copy the code
4.6 modify the ProductController
@RestController
public class ProductController {

    @Autowired
    private ProductService userService;

    @RequestMapping("/consumer")
    public ListProduct getUsers(@RequestParam("flag") Integer flag){
        returnuserService.getUsers(flag); }}Copy the code
4.7 Fuse Breaker Parameters

5. Isolation (thread pool isolation)

5.1 Creating a Project
5.2 Adding Coordinates
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency

Copy the code
5.3 Modifying the Configuration File
Name =eureka-consumer-ribbon-threadpool server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
5.4 Modifying a Startup Class
// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
5.5 modify ProductService
@Service
public class ProductService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;  //ribbon: load balancer

    @HystrixCommand(groupKey = "ego-product-provider",
            commandKey = "getUsers",
            threadPoolKey = "ego-product-provider".// Prefixes the thread name
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "30"),// Thread pool size
                    @HystrixProperty(name = "maxQueueSize", value = "100"),// Maximum queue length
                    @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),// Thread lifetime
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15")// Reject the request
            },
            fallbackMethod = "fallback")
    public ListProduct getUsers(a) {

        System.out.println(Thread.currentThread().getName());
        // Select the name of the service to invoke
        //ServiceInstance: encapsulates basic service information, such as the IP address and port number
        ServiceInstance si = loadBalancerClient.choose("ego-product-provider");
        // Concatenate the URL to access the service
        StringBuffer sb = new StringBuffer();

        //http://localhost:9001/user/product/findAll
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/product/findAll");
        System.out.println(sb.toString());
        //SpringMVC RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReferenceListProduct type = new ParameterizedTypeReferenceListProduct() {
        };

        //ResponseEntity: encapsulates the return value information
        ResponseEntityListProduct entity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, type);
        return entity.getBody();
    }

    // The method that returns the base data
    public ListProduct fallback(a) {
        System.out.println(Thread.currentThread().getName());
        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        return list;
    }

    public void showThread(a){ System.out.println(Thread.currentThread().getName()); }}Copy the code
5.6 modify the ProductController
@RestController
public class ProductController {

    @Autowired
    private ProductService userService;

    @RequestMapping("/consumer")
    public ListProduct getUsers(a){
        return userService.getUsers();
    }

    @RequestMapping("/consumer1")
    public void getUsers1(a){ userService.showThread(); }}Copy the code
5.7 Thread pool isolation parameters

6. Isolation (semaphore isolation)

6.1 Creating a Project
6.2 Adding Coordinates
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency

Copy the code
6.3 Modifying the Configuration File
Name =eureka-consumer-ribbon semaphore server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
6.4 Modifying a Startup Class
// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
6.5 modify ProductService
@Service
public class ProductService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;  //ribbon: load balancer

    @HystrixCommand(groupKey = "ego-product-provider",
            commandKey = "getUsers",
            threadPoolKey = "ego-product-provider".// Prefixes the thread name
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "30"),// Thread pool size
                    @HystrixProperty(name = "maxQueueSize", value = "100"),// Maximum queue length
                    @HystrixProperty(name = "keepAliveTimeMinutes", value = "2"),// Thread lifetime
                    @HystrixProperty(name = "queueSizeRejectionThreshold", value = "15")// Reject the request
            },
            fallbackMethod = "fallback")
    public ListProduct getUsers(a) {

        System.out.println(Thread.currentThread().getName());
        // Select the name of the service to invoke
        //ServiceInstance: encapsulates basic service information, such as the IP address and port number
        ServiceInstance si = loadBalancerClient.choose("ego-product-provider");
        // Concatenate the URL to access the service
        StringBuffer sb = new StringBuffer();

        //http://localhost:9001/user/product/findAll
        sb.append("http://").append(si.getHost()).append(":").append(si.getPort()).append("/product/findAll");
        System.out.println(sb.toString());
        //SpringMVC RestTemplate
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReferenceListProduct type = new ParameterizedTypeReferenceListProduct() {
        };

        //ResponseEntity: encapsulates the return value information
        ResponseEntityListProduct entity = restTemplate.exchange(sb.toString(), HttpMethod.GET, null, type);
        return entity.getBody();
    }

    // The method that returns the base data
    public ListProduct fallback(a) {
        System.out.println(Thread.currentThread().getName());
        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        return list;
    }

    public void showThread(a){ System.out.println(Thread.currentThread().getName()); }}Copy the code
6.6 Semaphore Isolation Parameters

Differences between thread pool isolation and semaphore isolation

Feign's avalanche treatment

1.Feign service degradation processing

1.1 Creating a Project
1.2 Modifying the Configuration File
Name =springcloud-eureka-consumer-feign-fallback server.port=9020 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ #feign By default, hystrix is not enabled. The default value is false feign.hystrix.enabled=trueCopy the code
1.3 modify ProductConsumerService
// Specify the service that implements this interface
@FeignClient(name = "ego-product-provider", fallback = ProductServiceFallback.class)
public interface ProductConsumerService {

    // Query all items
    @RequestMapping(value = "/product/findAll", method = RequestMethod.GET)
    public ListProduct findAll(a);
}

Copy the code
1.4 add ProductServiceFallback
@Component
public class ProductServiceFallback implements ProductConsumerService {

    /** * A fallback method that returns the base data *@return* /
    @Override
    public ListProduct findAll(a) {

        ArrayListProduct list = new ArrayList();
        list.add(new Product(-1."I'm the bottom line."));
        returnlist; }}Copy the code
1.5 modify the ProductController
@RestController
public class ProductController {

    @Autowired
    private ProductConsumerService consumerService;
    /** * Select * from Consumer@return* /
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ListProduct list(a){
        returnconsumerService.findAll(); }}Copy the code

2. Abnormal records after the downgrade

2.1 Creating a Project
2.2 add ProductServiceFallbackFactory class
@Component
public class ProductServiceFallbackFactory implements FallbackFactoryProductConsumerService {

    Logger logger = LoggerFactory.getLogger(ProductServiceFallbackFactory.class);
    @Override
    public ProductConsumerService create(final Throwable throwable) {

        return new ProductConsumerService() {
            /** * A fallback method that returns the base data *@return* /
            @Override
            public ListProduct findAll(a) {
                logger.warn("Fallback Exception: ", throwable);
                ArrayListProduct list = new ArrayList();
                list.add(new Product(-1."I'm the bottom line."));
                returnlist; }}; }}Copy the code
2.3 modify ProductConsumerService
// Specify the service that implements this interface
@FeignClient(name = "ego-product-provider", fallbackFactory = ProductServiceFallbackFactory.class)
public interface ProductConsumerService {

    // Query all items
    @RequestMapping(value = "/product/findAll", method = RequestMethod.GET)
    public ListProduct findAll(a);
}

Copy the code

Visual data monitoring hystrix-Dashboard

Hystrix-dashboard is a real-time monitoring tool for Hystrix. Through the Hystrix-Dashboard, you can intuitively view the request response time and request success rate of each Hystrix Command.

1. Create projects

2. Add coordinates

?xml version="1.0" encoding="UTF-8"? 
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    modelVersion4.0.0/modelVersion
    parent
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-parent/artifactId
        version1.5.13. RELEASE/version
        relativePath / ! -- lookup parent from repository --
    /parent
    groupIdcom.luyi/groupId
    artifactIdspringcloud-eureka-consumer-ribbon-dashboard/artifactId
    version0.0.1 - the SNAPSHOT/version
    namespringcloud-eureka-consumer-ribbon-dashboard/name
    descriptionDemo project for Spring Boot/description

    properties
        java.version1.8/java.version
    /properties

    dependencyManagement
        dependencies
            dependency
                groupIdorg.springframework.cloud/groupId
                artifactIdspring-cloud-dependencies/artifactId
                versionDalston.SR5/version
                typepom/type
                scopeimport/scope
            /dependency
        /dependencies
    /dependencyManagement
    dependencies
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-web/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-test/artifactId
            scopetest/scope
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-config/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-eureka/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-actuator/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix-dashboard/artifactId
        /dependency

    /dependencies

    build
        plugins
            plugin
                groupIdorg.springframework.boot/groupId
                artifactIdspring-boot-maven-plugin/artifactId
            /plugin
        /plugins
    /build

/project

Copy the code

3. Modify the startup class

// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
@EnableHystrixDashboard
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code

Access:http://localhost:9010/hystrix.streamCheck the information

4.Hystrix-dashboard monitoring center

4.1 Creating a Project
4.2 Adding Coordinates
?xml version="1.0" encoding="UTF-8"? 
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    modelVersion4.0.0/modelVersion
    parent
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-parent/artifactId
        version1.5.13. RELEASE/version
        relativePath / ! -- lookup parent from repository --
    /parent
    groupIdcom.luyi/groupId
    artifactIdspringcloud-eureka-consumer-dashboard-view/artifactId
    version0.0.1 - the SNAPSHOT/version
    namespringcloud-eureka-consumer-dashboard-view/name
    descriptionDemo project for Spring Boot/description

    properties
        java.version1.8/java.version
    /properties

    dependencyManagement
        dependencies
            dependency
                groupIdorg.springframework.cloud/groupId
                artifactIdspring-cloud-dependencies/artifactId
                versionDalston.SR5/version
                typepom/type
                scopeimport/scope
            /dependency
        /dependencies
    /dependencyManagement
    dependencies
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-web/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-test/artifactId
            scopetest/scope
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-config/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-eureka/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-actuator/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix-dashboard/artifactId
        /dependency

    /dependencies

    build
        plugins
            plugin
                groupIdorg.springframework.boot/groupId
                artifactIdspring-boot-maven-plugin/artifactId
            /plugin
        /plugins
    /build

/project

Copy the code
4.3 Modifying the Configuration File
Name =eureka-consumer-hystrix-dashboard server.port=1001 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/Copy the code
4.4 Modifying a Startup Class
// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
@EnableHystrixDashboard
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
4.5 Startup Sequence

Start Dashboard first and then dashboard-View

4.6 Accessing the Monitoring Center

Access: localhost: 1001 / hystrix

4.7 Monitoring center Diagram

6. Use Turbine to collect data for monitoring in multiple services and clusters

Turbine is a tool for aggregation servers to send event stream data. In hystrix's monitoring, only a single node can be monitored. In actual production, all nodes are clusters, so Turbine can be used to monitor cluster services.

‚Äč

1. Create Turbine projects

1.1 Adding Coordinates
?xml version="1.0" encoding="UTF-8"? 
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    modelVersion4.0.0/modelVersion
    parent
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-parent/artifactId
        version1.5.13. RELEASE/version
        relativePath / ! -- lookup parent from repository --
    /parent
    groupIdcom.luyi/groupId
    artifactIdspringcloud-eureka-consumer-turbine/artifactId
    version0.0.1 - the SNAPSHOT/version
    namespringcloud-eureka-consumer-turbine/name
    descriptionDemo project for Spring Boot/description

    properties
        java.version1.8/java.version
    /properties

    dependencyManagement
        dependencies
            dependency
                groupIdorg.springframework.cloud/groupId
                artifactIdspring-cloud-dependencies/artifactId
                versionDalston.SR5/version
                typepom/type
                scopeimport/scope
            /dependency
        /dependencies
    /dependencyManagement
    dependencies
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-web/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-test/artifactId
            scopetest/scope
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-config/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-eureka/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-actuator/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix-dashboard/artifactId
        /dependency

        ! Add turbine coordinates --
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-turbine/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-netflix-turbine/artifactId
        /dependency

    /dependencies

    build
        plugins
            plugin
                groupIdorg.springframework.boot/groupId
                artifactIdspring-boot-maven-plugin/artifactId
            /plugin
        /plugins
    /build

/project

Copy the code
1.2 Modifying the Configuration File
Name =eureka-consumer-hystrix-turbine server.port=1002 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - turbine -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - # configuration of Eureka serviceId list, AppConfig =eureka-consumer-ribbon-threadpool,springcloud-eureka-consumer-feign-fallback Use commas (,) to separate multiple entries. The default value is default. # use http://... /turbine.stream? One cluster = {clusterConfig} visit turbine. Aggregator. ClusterConfig = default # 1. ClusterNameExpression to specify the name of the cluster, the default expression appName; At this point: turbine. Aggregator. ClusterConfig need to be configured to monitor application name; # 2. When clusterNameExpression: default, turbine. Aggregator. ClusterConfig can not write, because the default is the default; # 3. When clusterNameExpression: metadata['cluster'], imagine that the application to be monitored is configured with eureka.instance.metadata-map.cluster: ABC, # you will need to configure and turbine. The aggregator. ClusterConfig: ABC turbine. ClusterNameExpression = "default"Copy the code
1.3 Modifying the Startup Class
@SpringBootApplication
@EnableTurbine
public class HystrixTurbineApplication {
    public static void main(String[] args) { SpringApplication.run(HystrixTurbineApplication.class, args); }}Copy the code

2. Use Turbine to aggregate multiple services

2.1 Modify the POM file of the aggregated project and add the coordinates of Dashboard
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix/artifactId
/dependency
dependency
    groupIdorg.springframework.boot/groupId
    artifactIdspring-boot-actuator/artifactId
/dependency
dependency
    groupIdorg.springframework.cloud/groupId
    artifactIdspring-cloud-starter-hystrix-dashboard/artifactId
/dependency

Copy the code
2.2 Modifying startup Classes of monitored services
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
// The following two annotations must be added
@EnableCircuitBreaker
@EnableHystrixDashboard
public class ConsumerApplication {

    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code
2.3 Check turbine's monitoring address after successful integration

Look at: http://localhost:1002/turbine.stream

Use RabbitMQ to collect and monitor data

The tight coupling between turbine and services can be solved with RabbitMQ, and tuebine requires the names of the services to be collected in the configuration file, which can be difficult to configure if there are many services.

Create a Consumer service

2. Add coordinates

?xml version="1.0" encoding="UTF-8"? 
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    modelVersion4.0.0/modelVersion
    parent
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-parent/artifactId
        version1.5.13. RELEASE/version
        relativePath / ! -- lookup parent from repository --
    /parent
    groupIdcom.luyi/groupId
    artifactIdspringcloud-eureka-consumer-ribbon-dashboard-mq/artifactId
    version0.0.1 - the SNAPSHOT/version
    namespringcloud-eureka-consumer-ribbon-dashboard-mq/name
    descriptionDemo project for Spring Boot/description

    properties
        java.version1.8/java.version
    /properties

    dependencyManagement
        dependencies
            dependency
                groupIdorg.springframework.cloud/groupId
                artifactIdspring-cloud-dependencies/artifactId
                versionDalston.SR5/version
                typepom/type
                scopeimport/scope
            /dependency
        /dependencies
    /dependencyManagement
    dependencies
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-web/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-test/artifactId
            scopetest/scope
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-config/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-eureka/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-actuator/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix-dashboard/artifactId
        /dependency

        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-netflix-hystrix-stream/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-stream-rabbit/artifactId
        /dependency

    /dependencies

    build
        plugins
            plugin
                groupIdorg.springframework.boot/groupId
                artifactIdspring-boot-maven-plugin/artifactId
            /plugin
        /plugins
    /build

/project

Copy the code

3. Modify the consumer configuration file

Name =eureka-consumer-ribbon-dashboard server.port=9010 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ Spring. The rabbitmq. Host = 192.168.234.128 spring. The rabbitmq. Port = 5672 spring. The rabbitmq. Username = luyi spring.rabbitmq.password=luyi spring.rabbitmq.virtual-host=/Copy the code

4. Modify the startup class

// Turn on the fuse
@EnableCircuitBreaker
// Represents the client of Eureka
@EnableEurekaClient
@SpringBootApplication
@EnableHystrix
@EnableHystrixDashboard
public class ConsumerApplication {
    public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}Copy the code

5. Create Turbine projects

6. Add dependencies to Turbine projects

?xml version="1.0" encoding="UTF-8"? 
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 https://maven.apache.org/xsd/maven-4.0.0.xsd"
    modelVersion4.0.0/modelVersion
    parent
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-parent/artifactId
        version1.5.13. RELEASE/version
        relativePath / ! -- lookup parent from repository --
    /parent
    groupIdcom.luyi/groupId
    artifactIdspringcloud-eureka-consumer-turbine-mq/artifactId
    version0.0.1 - the SNAPSHOT/version
    namespringcloud-eureka-consumer-turbine-mq/name
    descriptionDemo project for Spring Boot/description

    properties
        java.version1.8/java.version
    /properties

    dependencyManagement
        dependencies
            dependency
                groupIdorg.springframework.cloud/groupId
                artifactIdspring-cloud-dependencies/artifactId
                versionDalston.SR5/version
                typepom/type
                scopeimport/scope
            /dependency
        /dependencies
    /dependencyManagement
    dependencies
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-web/artifactId
        /dependency
        dependency
            groupIdorg.springframework.boot/groupId
            artifactIdspring-boot-starter-test/artifactId
            scopetest/scope
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-config/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-hystrix/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-turbine-stream/artifactId
        /dependency
        dependency
            groupIdorg.springframework.cloud/groupId
            artifactIdspring-cloud-starter-stream-rabbit/artifactId
        /dependency

    /dependencies

    build
        plugins
            plugin
                groupIdorg.springframework.boot/groupId
                artifactIdspring-boot-maven-plugin/artifactId
            /plugin
        /plugins
    /build

/project

Copy the code

7. Modify Turbine's configuration file

Name =eureka-consumer-hystrix-turbine server.port=1002 Register with all registries eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/ Host =192.168.234.128 spring.rabbitmq.port=5672 spring.rabbitmq.username=luyi spring.rabbitmq.password=luyi spring.rabbitmq.virtual-host=/Copy the code

8. Modify Turbine startup class

@SpringBootApplication
@EnableTurbineStream
public class HystrixTurbineApplication {
    public static void main(String[] args) { SpringApplication.run(HystrixTurbineApplication.class, args); }}Copy the code
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.