十年網(wǎng)站開發(fā)經(jīng)驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網(wǎng)站問題一站解決
這篇文章主要介紹了Spring Cloud Feign怎么用,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
概述
在Spring Cloud EureKa Ribbon 服務注冊-發(fā)現(xiàn)-調(diào)用一文中簡單的介紹了在Spring Cloud中如何使用EureKa和Ribbon。文章中使用了RestTemplate去訪問其他的restful微服務接口。其實在Spring Cloud還可以使用Feign來訪問其他的restful微服務接口。使用起來更加的簡潔明了。
集成Feign
修改一下Spring Cloud EureKa Ribbon 服務注冊-發(fā)現(xiàn)-調(diào)用中order service的pom配置,把Fegin引入進來即可。
org.springframework.cloud spring-cloud-starter-feign
修改OrderApplication類,刪除如下代碼:
@Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }
并加上@EnableFeignClients注解。完整代碼如下:
package com.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @EnableDiscoveryClient @EnableFeignClients @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
新增接口UserService,并使用@FeignClient注解。
package com.springboot; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name="user") public interface UserService { @GetMapping(value="/getUser") String getUser(); }
這里的@FeignClient(name="user")中的name=user表示要訪問user這個微服務。由于order這個微服務已經(jīng)集成了Eureka和Ribbon。那么使用@FeignClient(name="user")訪問user微服務的時候,已經(jīng)自動支持客戶端路由了。并且會從注冊中心中找到user這個微服務。
修改OrderController,注入UserService。
package com.springboot; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class OrderController { @Autowired private UserService userService; @GetMapping("/getOrderUser") public String getOrderUser() { return userService.getUser(); } }
這樣就無需使用
restTemplate.getForEntity("http://user/getUser",String.class).getBody();
來調(diào)用user服務中的getUser接口了。而是直接使用userService.getUser()就可以了。
啟動注冊中心以及user和order這兩個微服務。使用http://localhost:8883/getOrderUser
訪問一下。是可以返回
I am user list.
感謝你能夠認真閱讀完這篇文章,希望小編分享的“Spring Cloud Feign怎么用”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關知識等著你來學習!