Hystrix的使用2-服務降級fallback

Hystrix的使用2-服務降級fallback

1.定義

我們可以給被調用的方法設置一個降級方法,在調用方法失敗或者超時後,Hystrix會調用這個降級方法。

2.代碼實現

2.1 父工程POM文件

  <packaging>pom</packaging>

  <modules>
    <module>cloud-provider-payment-hystrix8001</module>
  </modules>


  <!-- 統一管理jar包版本 -->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <junit.version>4.12</junit.version>
    <log4j.version>1.2.17</log4j.version>
    <lombok.version>1.16.18</lombok.version>
    <spring.boot.version>2.2.2.RELEASE</spring.boot.version>
    <spring.cloud.version>Hoxton.SR1</spring.cloud.version>
    <liuhangs.cloud.api.version>1.0.0-SNAPSHOT</liuhangs.cloud.api.version>
  </properties>

  <distributionManagement>
    <site>
      <id>website</id>
      <url>scp://webhost.company.com/www/website</url>
    </site>
  </distributionManagement>

  <!-- 子模塊繼承之後,提供作用:鎖定版本 + 子module不用謝groupId和version -->
  <dependencyManagement>
    <dependencies>
      <!--spring boot 2.2.2-->
      <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.2.2.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--spring cloud Hoxton.SR1-->
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>Hoxton.SR1</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <!--Spring cloud alibaba 2.1.0.RELEASE-->
      <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-alibaba-dependencies</artifactId>
        <version>2.1.0.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

2.2 hystrix8001工程POM文件

我們新建cloud-provider-payment-hystrix8001服務提供者工程。下一節服務熔斷還會用到此工程。

    <dependencies>
        <!-- hystrix依賴 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>
        <!-- 這是一個公共工程,定義了一些公用類 -->
        <dependency>
            <groupId>com.liuhangs.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${liuhangs.cloud.api.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--監控-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.3 hystrix8001工程application.yml

server:
  port: 8001

spring:
  application:
    # 服務名
    name: cloud-provider-payment-hystrix

2.4 hystrix8001工程service

2.4.1 服務接口PaymentHystrixService

import com.liuhangs.springcloud.api.entities.CommonResult;

/**payment服務接口
 */
public interface PaymentHystrixService {

    /**
     * 正常方法
     * @param id
     * @return
     */
    public CommonResult getPaymentOK(Long id);

    /**
     * 超時方法
     * @param id
     * @return
     */
    public CommonResult getPaymentTimeOut(Long id);
}

2.4.1 服務實現類PaymentHystrixServiceImpl

在需要加入服務降級的方法上增加@HystrixCommand註解,在註解中配置fallbackMethod屬性值,來指定對應的服務降級方法。

import com.liuhangs.springcloud.api.entities.CommonResult;
import com.liuhangs.springcloud.payment.service.PaymentHystrixService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**這個類裏包含服務降級的測試
 */
@Service
@Slf4j
public class PaymentHystrixServiceImpl implements PaymentHystrixService {

    @Value("${server.port}")
    private String SERVER_PORT;

    @Override
    public CommonResult getPaymentOK(Long id)
    {
        return new CommonResult(200, "請求ID爲:" + id + ", 當前線程是:" + Thread.currentThread().getName() +
                "," +
                " " +
                "服務端口:" +
                SERVER_PORT);
    }

    /**
     * 超過3000毫秒或者報錯就進入降級方法getPaymentTimeOutHandler
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "getPaymentTimeOutHandler", commandProperties =
            {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",
                    value = "3000")})  //@HystrixProperty中的配置表示調用此方法3秒後直接降級
    @Override
    public CommonResult getPaymentTimeOut(Long id)
    {
        //測試報錯進入降級方法
        //int a = 1/0;
        //測試超時進入降級方法
        try
        {
            TimeUnit.MILLISECONDS.sleep(5000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return new CommonResult(200, "請求ID爲:" + id + ", 當前線程是:" + Thread.currentThread().getName() + ", 服務端口:" +
                SERVER_PORT + ", 線程睡眠3秒");
    }

    /**
     * 服務降級後調用的方法
     * @param id
     * @return
     */
    public CommonResult getPaymentTimeOutHandler(Long id)
    {
        return new CommonResult(200, "請求ID爲:" + id + ", 當前線程是:" + Thread.currentThread().getName() + ", 服務端口:" +
                SERVER_PORT + ", 已經進入降級方法");
    }
}

2.5 hystrix8001工程controller

import com.liuhangs.springcloud.api.entities.CommonResult;
import com.liuhangs.springcloud.api.entities.Payment;
import com.liuhangs.springcloud.payment.service.PaymentHystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**服務降級測試controller
 */
@RequestMapping("provider/payment/hystrix")
@RestController
public class PaymentHystrixController {

    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/ok/{id}")
    public CommonResult getPaymentOK(@PathVariable("id") Long id)
    {
        return paymentHystrixService.getPaymentOK(id);
    }

    @GetMapping("/timeout/{id}")
    public CommonResult getPaymentTimeOut(@PathVariable("id") Long id)
    {
        return paymentHystrixService.getPaymentTimeOut(id);
    }
}

2.6 hystrix8001工程啓動類

/**服務啓動類
 */
@SpringBootApplication
@EnableCircuitBreaker  //使用Hystrix需要開啓熔斷註解
public class PaymentHystrixStart8001 {

    public static void main(String[] args)
    {
        SpringApplication.run(PaymentHystrixStart8001.class, args);
    }
}

2.7 測試

啓動工程。

2.7.1 調用正常方法

在瀏覽器中訪問 http://localhost:8001/provider/payment/hystrix/ok/1 直接返回成功。

2.7.2 測試超時情況

PaymentHystrixServiceImpl#getPaymentTimeOut的方法配置了超時時間爲3000毫秒,但是在進入方法後睡眠了5000毫秒,調用這個方法會超時,就會進入@HystrixCommand註解配置的fallbackMethod降級方法。
在瀏覽器中輸入 http://localhost:8001/provider/payment/hystrix/timeout/1 鏈接,可以看到下圖的返回值:

我們可以看出先是一直在等待接口返回,到了3秒後進入降級方法。

2.7.3 測試報錯情況

我們註釋掉PaymentHystrixServiceImpl#getPaymentTimeOut方法中的睡眠5秒的代碼,將 //int a = 1/0; 代碼的註釋打開。重啓服務,在瀏覽器中輸入 http://localhost:8001/provider/payment/hystrix/timeout/1 鏈接,得到如下返回:

可以看到方法報錯,同樣進入降級方法。

3.代碼請見

https://github.com/ainydexiaohai/cloud2020

4.參考文章

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章