您的位置:首页 > 编程语言 > Java开发

Spring Cloud 的 Hystrix 在 Feign上使用 Hystrix功能

2017-09-10 11:38 1011 查看
前文中使用注解@HystrixCommand的fallbackMethod属性实现回退的。然而,Feign是以接口形式工作的,它没有方法体,前文讲的方式显然不适合用于Feign。

现解决办法:

一、Feign接口

package com.itmuch.cloud;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name="cloud-service", fallback = FeignClientFallbackFactory.class)   // 服务端提供者的name
public interface UserFeignClient {

// @RequestLine("GET /get/{id}")
// public User findById(@Param("id") Long id);    // 此方式不适合于 Hystrix
@RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public User findById(@PathVariable("id") Long id);

}


二、Feign实现类

package com.itmuch.cloud;

import org.springframework.stereotype.Component;

@Component
public class FeignClientFallbackFactory implements UserFeignClient {

@Override
public User findById(Long id) {
User user = new User();
user.setId(-1L);
user.setName("NULL");
return user;
}

}


三、坑

问题产生原因

首先,使用spring-cloud搭建微服务的过程大部分是根据网上的教程来的,由于网上教程的时间较早,而spring-cloud更新迭代较快,会造成依赖上的一些问题。教程中的spring-cloud的依赖是

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>


而我自己使用idea搭建项目使用的是较新的依赖

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>


发现两者的区别了吗?对!就是依赖版本不同。教程中的版本是
Brixton.RELEASE
而我使用的版本是
Dalston.RELEASE


解决方案

如果是yml文件,请在文件中加入:

feign:
hystrix:
enabled: true


如果是properties文件,请在文件中加入:
feign.hystrix.enabled=true


重启服务,大功告成!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: