1. 在pom.xml 中 添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2. appcation 中开启断路器
@EnableEurekaClient
@EnableFeignClients
@EnableHystrix
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
3. yml 中配置断路器
feign:
hystrix:
enabled: true
4. 写本服务调用其他服务的远程接口
package....;
import ...SpareDetail;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
@Component
@FeignClient(name = "spare",fallback =ConfigServiceHystrix.class)
public interface SpareRemote {
// 这个路径 是远程接口的路径 我们这里一定要保证 和提供方保持一致
@PostMapping("/remote/get-by-ids/")
List<SpareDetail> getSpareListByIds(@RequestBody List<String> ids);
}
5. 实现降级方法
先写一个类,一定要加@Component,该类实现上面那个接口,实现里面所有的抽象方法,名字一定要一样,一定要有@Override
package...remote;
import ...SpareDetail;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author
* @ClassName: ConfigServiceHystrix
* @Description: 熔断器
* @date 2019年9月2日
*/
@Component
public class ConfigServiceHystrix implements SpareRemote{
@Override
public List<SpareDetail> getSpareListByIds(@RequestBody List<String> ids){
List<SpareDetail> SpareDetailList = ids.stream().map(id -> {
SpareDetail sd = new SpareDetail();
sd.setId(id);
sd.setSpareName("查询备品数据失败");
return sd;
}).collect(Collectors.toList());
return SpareDetailList;
};
}
6 controller 里调用吧
@RestController
public class TestController {
@Autowired
private SpareRemote spareRemote;
@GetMapping("/test")
public List<SpareDetail> test(){
//根据ids 获取 spareList
ArrayList<String> ids = new ArrayList<>();
ids.add("8b483c741c87f1385af4181e85c0c4da");
ids.add("d6640856e7f40689a52995426cf3d91b");
// 调取
List<SpareDetail> spareListByIds = spareRemote.getSpareListByIds(ids);
return spareListByIds;
}
}
7.使用工具测试一下controller提供的接口
直接看结果
[{
“spareId”: “8b483c741c87f1385af4181e85c0c4da”,
“spareName”: “查询备品备件数据失败”
},
{
“spareId”: “d6640856e7f40689a52995426cf3d91b”,
“spareName”: “查询备品备件数据失败”
}]