天天看點

每天20分鐘之hystrix概述提供的功能

概述

hystrix是奈飛開源的熔斷限流元件,雖然線上停止了維護,但是使用的使用者還是挺多的

很多線上的系統還在使用它。

它的原理是基于rxjava啟動線程池(信号量)去處理每個請求,做到服務的隔離

提供的功能

1 基礎應用

package cn.beckbi;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixThreadPoolProperties;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class Example1 extends HystrixCommand<String>
{

    private String name;

    public Example1(String  name) {
        super(
                HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(name))
                        .andCommandPropertiesDefaults(
                                HystrixCommandProperties.Setter()
                                        .withExecutionIsolationStrategy(
                                                HystrixCommandProperties.ExecutionIsolationStrategy.THREAD
                                        )
                        ).andThreadPoolPropertiesDefaults(
                        HystrixThreadPoolProperties.Setter()
                        .withCoreSize(10)
                        .withMaxQueueSize(100)
                        .withMaximumSize(100)
                )
        );
        this.name = name;
    }

    @Override
    protected String run() {
        /*
        try{
            TimeUnit.MICROSECONDS.sleep(1);
        }catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        System.out.println("get data");
        return "HystrixCommandName:"+this.name+"## currentThreadName="+Thread.currentThread().getName();
    }

    @Override
    protected String getFallback() {
        return Thread.currentThread().getName()+"失敗了";
    }

    @Override
    protected String getCacheKey() {
        return String.valueOf(this.name);
    }

    public static void main(String[] args) throws Exception{

        HystrixRequestContext hystrixRequestContext = HystrixRequestContext.initializeContext();

        Example1 example1 = new Example1("test1");
        String result = example1.execute();
        System.out.println("## currentThreadName="+Thread.currentThread().getName());
        System.out.println(result);

        Future<String> future = new Example1("test2").queue();
        System.out.println("future:"+future.get());



        result = new Example1("test3").execute();

        future = new Example1("test3").queue();
        System.out.println("future:"+future.get());
        hystrixRequestContext.shutdown();



    }
}           

複制

2 在spring-cloud中使用hystrix

服務中使用

@GetMapping("/user/{uid}")
    @HystrixCommand(fallbackMethod = "defaultCall",
    commandProperties = {
            @HystrixProperty(
                    name = "execution.isolation.strategy",
                    value = "THREAD"
            )
    })
    public String info(@PathVariable long uid) throws JsonProcessingException {

        @Data
        class IdData {
            private String id;
            private Long uid;
        }

        IdData idData = new IdData();
        idData.setUid(uid);
        idData.setId("123");
        return mapper.writeValueAsString(idData);
    }

    public String defaultCall(long uid) {
        return "failed:"+uid;
    }           

複制

也可以和feigin一起使用

3 htstrix監控和檢視監控資料

  1. 加入依賴 <dependency>

    <groupId>com.netflix.hystrix</groupId>

    <artifactId>hystrix-metrics-event-stream</artifactId>

    <version>${hystrix-core.version}</version>

    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-hystrix-dashboard -->

    <dependency>

    <groupId>org.springframework.cloud</groupId>

    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>

    <version>2.2.10.RELEASE</version>

    </dependency>

    @EnableHystrixDashboard

    @EnableHystrix

    @SpringBootApplication

  2. 增加監控

通路線上端口http://127.0.0.1:7330/hystrix

每天20分鐘之hystrix概述提供的功能

image.png

輸入監控頁面http://127.0.0.1:7330/actuator/hystrix.stream

配置頁面

http://127.0.0.1:7330/hystrix/monitor?stream=http%3A%2F%2F127.0.0.1%3A7330%2Factuator%2Fhystrix.stream

服務監控

spring.application.name=khystrix-spring
server.port=7330
management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env,beans
hystrix.dashboard.proxy-stream-allow-list=localhost           

複制

每天20分鐘之hystrix概述提供的功能

image.png