前文中使用注解@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
重启服务,大功告成!