一、Feign的介紹
Feign一般比較書面的解釋是:Feign是一個聲明式的WebService客戶端,使用Feign編寫的WebService客戶端更加簡單,他的使用方法是定義一個接口,然后在上線添加注解,,同事也支持JAX-RX標准的注解,Feign也支持可拔插式的編碼器和解碼器,Spring Cloud對Feign進行了封裝,使其支持了Spring MVC標准直接和HttpMessageConverters。Feign可以與Eureka和Ribbon組合使用一支持負載均衡。
Feign和Ribbon的區別是:
簡單的說,ribbon是直接通過微服務的地址調用服務,Feign是通過調用接口來進行調用服務。下面我就來根據二者的代碼來分析兩者的區別:
二、Feign的服務調用與Ribbon的服務調用
1.Ribbon的調用模式
a.導入maven
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency>
b.創建一個RestBean注入RestTemplate,不直接注入到controller層的原因是:我們還會為RestTemplate注入其他的屬性
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的調用模式是直接通過響應為服務的地址進行訪問
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的接口沒有自己去實現,而是直接去調用生產者的接口地址。