天天看点

SpringCloud中Hystrix的使用方式及注意事项

SpringCloud中Hystrix的使用方式及注意事项

  • ​​写在前面​​
  • ​​一、springCloud 集成 HystrixCommand​​
  • ​​1.1、集成方式​​
  • ​​1.2、新建Maven工程​​
  • ​​1.3、配置 Hystrix(服务的降级回调)​​
  • ​​1.4、模拟请求测试​​
  • ​​二、springCloud + RestTemplate + HystrixCommand 实现​​
  • ​​三、springCloud + feignClient + Hystrix 实现​​
  • ​​三、[Demo代码,可以参照这里](https://github.com/tonels/Microservices/tree/ls-eurekaCloud)​​
  • ​​四、注意事项​​
  • ​​4.1、版本依赖(检查)​​
  • ​​4.2、常见问题​​

写在前面

版本依赖问题,基于Spring Cloud的微服务架构,必须考虑和慎重的问题,就是检查版本依赖的问题,我们很多时候,百度或者谷歌别人的代码实现的时候,面临最多的问题也是,我们和参照的示例环境其实是不一样的…这个在解决问题时,也是要考虑的问题。

一、springCloud 集成 HystrixCommand

1.1、集成方式

搜索Maven中央仓库,发现两个类似的东西

SpringCloud中Hystrix的使用方式及注意事项

通过查找,发现

SpringCloud中Hystrix的使用方式及注意事项

还有这个starter的起始依赖,包括以下几个包的实现封装

SpringCloud中Hystrix的使用方式及注意事项

1.2、新建Maven工程

SpringCloud中Hystrix的使用方式及注意事项

添加依赖 jar

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.3.1.RELEASE</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-test</artifactId>
            <scope>test</scope>
        </dependency>      

1.3、配置 Hystrix(服务的降级回调)

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@EnableHystrix
@RestController
public class Hystrix {
    public static void main(String[] args) {
        SpringApplication.run(Hystrix.class, args);
    }

    @RequestMapping(value = "/")
    @HystrixCommand(fallbackMethod = "fallback_hello",
            commandProperties = {
                @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000")
            }
    )
    public String hello() throws InterruptedException {
        Thread.sleep(2000);
        return "Welcome Hystrix";
    }
    private String fallback_hello() {
        return "请求失败,响应超时...";
    }
}      

1.4、模拟请求测试

这里可以试着去修改过时时间限制,也就是请求在多少时间内,不响应,即触发降级回调方法

可以发现,当正常响应式,页面返回

SpringCloud中Hystrix的使用方式及注意事项

二、springCloud + RestTemplate + HystrixCommand 实现

这里代码不方便贴了,可以在Github看到      

三、springCloud + feignClient + Hystrix 实现

这里代码不方便贴了,可以在Github看到      

三、​​Demo代码,可以参照这里​​

四、注意事项

4.1、版本依赖(检查)

4.2、常见问题

  • feignClient的请求 URL和参数映射
  • 尽量使用@RequestMapping()注解
  • 自定义fallback时,加上@Compoent注解
  • 使用feignClient时,要把 feign.hystrix.enabled=true 设置打开