使用HystrixCommand封裝http請求


1.引入依賴

  要排除hystrix-core里的archaius-core,否則報錯

<dependency>
          <groupId>com.netflix.hystrix</groupId>
          <artifactId>hystrix-core</artifactId>
          <version>1.5.12</version>
         <exclusions>
              <exclusion>
                  <artifactId>archaius-core</artifactId>
                  <groupId>com.netflix.archaius</groupId>
              </exclusion>
          </exclusions>
      </dependency>

     <dependency>
          <groupId>com.netflix.archaius</groupId>
          <artifactId>archaius-core</artifactId>
          <version>0.7.4</version>
      </dependency>

      <dependency>
          <groupId>commons-lang</groupId>
          <artifactId>commons-lang</artifactId>
          <version>2.6</version>
      </dependency>

 

2.定義HttpHystrixCommand類

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.exception.HystrixRuntimeException;
import com.netflix.hystrix.exception.HystrixTimeoutException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HttpHystrixCommand extends HystrixCommand<ResponseEntity<String>> {

    private org.springframework.http.HttpMethod httpMethod;
    private HttpEntity httpEntity;
    private String url;
    private RestTemplate restTemplate = new RestTemplate();

    public HttpHystrixCommand(String url, HttpMethod httpMethod, HttpEntity<?> httpEntity) {
        // 設置3秒超時
        super(HystrixCommandGroupKey.Factory.asKey("http_hystrix_command_group_key"), 3000);
        this.httpMethod = httpMethod;
        this.httpEntity = httpEntity;
        this.url = url;
    }

    public HttpHystrixCommand(String url, HttpEntity<?> httpEntity) {
        this(url, HttpMethod.POST, httpEntity);
    }

    public HttpHystrixCommand(String url) {
        this(url, HttpMethod.GET, null);
    }

    public ResponseEntity<String> post() {
        this.httpMethod = HttpMethod.POST;
        return execute();
    }

    public ResponseEntity<String> get() {
        this.httpMethod = HttpMethod.GET;
        this.httpEntity = null;
        return execute();
    }

    @Override
    protected ResponseEntity<String> run() throws Exception {
        // Thread.sleep(3000);
        return restTemplate.exchange(url, httpMethod, (HttpEntity) httpEntity, String.class);
    }

    @Override
    protected ResponseEntity<String> getFallback() {
        Throwable executionException = getExecutionException();
        if (executionException instanceof HystrixTimeoutException) {
            log.error("請求因超時融斷!url:{} param:{}", this.url, this.httpEntity, executionException);
        } else if (executionException instanceof HystrixRuntimeException) {
            log.error("請求直接融斷!url:{} param:{}", this.url, this.httpEntity, executionException);
        } else {
            log.error("請求異常!url:{} param:{}", this.url, this.httpEntity, executionException);
        }

        return new ResponseEntity<String>(org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

 

3.測試

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springside.modules.utils.mapper.JsonMapper;
import java.util.Collections;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 */

@Slf4j
public class HttpHystrixCommandTest {
    public static void main(String[] args) {
        ResponseEntity<String> response = new HttpHystrixCommand(
                "https://aaa.xxx.com/setting/get?key=key1&source=h5")
                .get();
        if (response.getStatusCode().value() == org.springframework.http.HttpStatus.OK.value()) {
            log.info("請求成功");
        }else{
            log.info("請求失敗");
        }
    }
    private static HttpHeaders defaultRequestHeaders = new HttpHeaders();

    static {
        defaultRequestHeaders.setContentType(MediaType.APPLICATION_JSON);
        defaultRequestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    }

    public static HttpEntity<String> getHttpEntity(Object postData) {
        return new HttpEntity<>(JsonMapper.INSTANCE.toJson(postData), defaultRequestHeaders);
    }

    public static HttpEntity<String> getHttpEntity(String postData) {
        return new HttpEntity<>(postData, defaultRequestHeaders);
    }
}

 

4.正常的返回如下

INFO HttpHystrixCommandTest - 請求成功

5.異常(增加代碼Thread.sleep(3000);)的返回如下:

ERROR HttpHystrixCommand - 請求因超時融斷!url:https://aaa.xxx.com/setting/get?key=depository&source=h5 param:null
com.netflix.hystrix.exception.HystrixTimeoutException: null


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM