微服務-(Hystrix斷路器)

一.hystrix是什麼

斷路器,可對請求次數響應時間進行降級處理。java

二.爲何用hyst rix

實現服務降級web

三.我怎麼去用hystrix

註解或配置spring

import com.netflix.hystrix.*;
import org.springframework.web.client.RestTemplate;

public class CommandForIndex extends HystrixCommand<Object> {



    private final RestTemplate template;

    private String id;

    public CommandForIndex(String id, RestTemplate restTemplate) {
        // java代碼配置, 只針對這個命令
        super(Setter
                // 必填項。指定命令分組名,主要意義是用於統計
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey("DnHello-Group"))
                // 依賴名稱(若是是服務調用,這裏就寫具體的接口名, 若是是自定義的操做,就本身命令),默認是command實現類的類名。 熔斷配置就是根據這個名稱
                .andCommandKey(HystrixCommandKey.Factory.asKey("ConsumerController"))
                // 線程池命名,默認是HystrixCommandGroupKey的名稱。 線程池配置就是根據這個名稱
                .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("DnUser-ThreadPool"))
                // command 熔斷相關參數配置
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                                // 配置隔離方式:默認採用線程池隔離。還有一種信號量隔離方式,
                                // .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
                                // 超時時間500毫秒
                                .withExecutionTimeoutInMilliseconds(100)

                        // 信號量隔離的模式下,最大的請求數。和線程池大小的意義同樣
                        // .withExecutionIsolationSemaphoreMaxConcurrentRequests(2)
                        // 熔斷時間(熔斷開啓後,各5秒後進入半開啓狀態,試探是否恢復正常)
                        // .withCircuitBreakerSleepWindowInMilliseconds(5000)
                )
                // 設置線程池參數
                .andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter()
                        // 線程池大小
                        .withCoreSize(1)
                        //容許最大的緩衝區大小
//                       .withMaxQueueSize(2)
                ));
        // super(HystrixCommandGroupKey.Factory.asKey("DnUser-command"),100);
        this.id = id;
        this.template = restTemplate;
    }

    @Override
    protected Object run() throws Exception {
        System.out.println("###command#######" + Thread.currentThread().toString());
        Object result =  template.getForObject("http://helloclient/user?id="+id+"",Object.class);
        System.out.println(
                "###command結束#######" + Thread.currentThread().toString() + ">><>>>執行結果:" + result.toString());
        return result;
    }

    @Override
    protected Object getFallback() {
        System.out.println("###降級啦####" + Thread.currentThread().toString());
        return "出錯了,我降級了";
        //降級的處理:
        //1.返回一個固定的值
        //2.去查詢緩存
        //3.調用一個備用接口
    }
}
相關文章
相關標籤/搜索