前文中使用註解@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
重啓服務,大功告成!