本文介紹了springcloud Feign的Hystrix支持,分享給大家,具體如下:
一、Feign client中加入Hystrix的fallback
1
2
3
4
5
6
7
8
9
10
11
12
|
@FeignClient (name= "springboot-h2" , fallback=HystrixClientFallback. class ) //在fallback屬性中指定斷路器的fallback public interface UserFeignClient { // @GetMapping("/user/{id}") @RequestMapping (value = "/user/{id}" , method = RequestMethod.GET) User findById( @PathVariable ( "id" ) Long id); @RequestMapping (value= "/users" , method=RequestMethod.GET) List<User> findAll(); @RequestMapping (value= "/post/user" , method=RequestMethod.POST) User save( @RequestBody User user); } |
二、編寫HystrixClientFallback類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Component //加入spring bean中 public class HystrixClientFallback implements UserFeignClient{ @Override public User findById(Long id) { User u = new User(); u.setName( "臨時名" ); u.setUsername( "匿名" ); return u; } @Override public List<User> findAll() { return null ; } @Override public User save(User user) { return null ; } } |
三、加入Hystrix支持
1
|
@EnableCircuitBreaker |
四、測試
不啟動底層依賴的服務,直接啟動服務,然后測試,發現瀏覽器中的結果為:
{"id":null,"username":"匿名","name":"臨時名","age":null,"balance":null}
并沒有像想象中的那樣報異常,而是進入了HystrixClientFallback類中的findById方法中。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/liuchuanhong1/article/details/55005446