上節寫了ribbon 整合hystrix的實例,本節準備實現feign,因爲比較簡單,只寫關鍵代碼,具體看github源碼java
建立fallback包存放feign的fallback處理類,包結構以下:git
UserFeignApi爲入口調用類github
package com.mayi.springcloud.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.mayi.springcloud.client.UserFeignClient; @RestController public class UserFeignApi { @Autowired private UserFeignClient userFeignClient; @GetMapping("/listUsersByFeign") public String ListUsers(){ String users = this.userFeignClient.listUsers(); return users; } }
UserFeignClient爲實現feign的接口web
package com.mayi.springcloud.client; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import com.mayi.springcloud.fallback.UserFallback; @FeignClient(name="service-user", fallback=UserFallback.class) public interface UserFeignClient { @GetMapping("/listUsers") public String listUsers(); }
UserFallback爲節點故障處理類spring
package com.mayi.springcloud.fallback; import org.springframework.stereotype.Component; import com.mayi.springcloud.client.UserFeignClient; @Component public class UserFallback implements UserFeignClient{ @Override public String listUsers() { // TODO Auto-generated method stub return "服務調用失敗"; } }
配置中心的service-feign-hystrix-dev.ymlapi
server: port: 1001 feign: hystrix: enabled: true
依次啓動下圖服務微信
訪問http://localhost:1001/listUsersByFeign,交替出現架構
手動中止其中一個service-user服務,當負載均衡至該節點,會轉到自定義的fallback類app
若干秒後,該故障節點會被剔除,以後不會被其餘調用者訪問到。負載均衡
源碼地址:https://github.com/tianyana/s...
歡迎加入JAVA架構師QQ羣(初建):618578034
接下來,我會依次更新文章,直至整個架構完成,若有興趣的朋友關注做者 或 加我微信 拉你進入spring cloud社區羣
微信公衆號:java架構師修行
本公衆號從2018-5.1日 - 2019.5.1日期間,將要按照JAVA高級軟件架構師實戰培訓的路線發佈一期完整的架構文章,難度由淺入深,適合有必定開發基礎想轉架構和正在作初級架構開發的人員學習(springcloud更新完畢即開始)