1、Feign的介紹java
Feign通常比較書面的解釋是:Feign是一個聲明式的WebService客戶端,使用Feign編寫的WebService客戶端更加簡單,他的使用方法是定義一個接口,而後在上線添加註解,,同事也支持JAX-RX標準的註解,Feign也支持可拔插式的編碼器和解碼器,Spring Cloud對Feign進行了封裝,使其支持了Spring MVC標準直接和HttpMessageConverters。Feign能夠與Eureka和Ribbon組合使用一支持負載均衡。web
Feign和Ribbon的區別是:spring
簡單的說,ribbon是直接經過微服務的地址調用服務,Feign是經過調用接口來進行調用服務。下面我就來根據兩者的代碼來分析二者的區別:restful
2、Feign的服務調用與Ribbon的服務調用
架構
1.Ribbon的調用模式app
a.導入maven 負載均衡
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency>
b.建立一個RestBean注入RestTemplate,不直接注入到controller層的緣由是:咱們還會爲RestTemplate注入其餘的屬性maven
import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; //這個註解表示將這個類注入到spring boot的容器中 @Configuration public class RestBean { @Bean @LoadBalanced //這個註解是Ribbon使用負載均衡的註解 public RestTemplate getRestTemplate() { return new RestTemplate(); } }
c.建立controller層,調用生產者服務微服務
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.List; @RestController public class RibbonController { //此處的請求前綴是微服務提供者的服務名稱,至關於localhost:8080 private static final String producter_url = "http://productor"; /** * 使用 使用restTemplate訪問restful接口很是的簡單粗暴無腦。 (url, requestMap, * ResponseBean.class)這三個參數分別表明 REST請求地址、請求參數、HTTP響應轉換被轉換成的對象類型。 */ @Autowired private RestTemplate restTemplate; @RequestMapping(value = "/consumer/dept/list") public List<String> list() { return restTemplate.getForObject(producter_url + "/show", List.class); } }
咱們能夠看見,Ribbon的調用模式是直接經過響應爲服務的地址進行訪問this
2.Feign的調用模式
a.導入maven
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
b.建立一個controller
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class FeignController { @Autowired private FeignService feignShow; @RequestMapping(value = "/show") public List<String> feignMain() { return this.feignShow.show(); } }
c.建立service
//這個註解表示要調用的微服務名稱 @FeignClient(value = "productor") public interface FeignService { //使用Feign方式調用服務,直接就能調用生產者接口的地址 @RequestMapping(value = "/show", method = RequestMethod.GET) List<String> show(); }
從上面兩個調用方式的對比咱們能夠看見:Ribbon中沒有使用service,而是經過RestTemplate直接經過地址訪問生產者的服務;Feign則是和咱們平時使用的架構同樣,只是service的接口沒有本身去實現,而是直接去調用生產者的接口地址。