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

写在前面

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

一、springCloud 集成 HystrixCommand

1.1、集成方式

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


通过查找,发现


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

1.2、新建Maven工程


添加依赖 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 + RestTemplate + HystrixCommand 实现

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

三、springCloud + feignClient + Hystrix 实现

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

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

四、注意事项

4.1、版本依赖(检查)

4.2、常见问题

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

相关推荐

卡卡罗特ovo:说起云智我就来气,约好了一面,结果面试官没来,ssob上问hr也未读,我还是专门请了半天假在家面试,恶心死了
点赞 评论 收藏
分享
03-16 11:07
南开大学 Java
牛马人的牛马人生:快手卡实习经历的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务