Feign概述
Feign是一個聲明式WebService客戶端。使用Feign能讓編寫Web Service客戶端更加簡單,它的使用方法是定義一個接口,然後在上面添加註解,同時也支持JAX-RS標準的註解。
Feign也支持可拔插式的編碼器和解碼器。SpringCloud對Feign進行了封裝,使其支持了Spring MVC標準註解和HttpMessageConverters。
Feign可以與Eureka和Ribbon組合使用以支持負載均衡。
Feign作用:
使用Ribbon+RestTemplate時,利用一套模板化的調用方法。但是在實際開發中,由於對服務依賴的調用可能不止一處,往往一個接口會被多出調用,所以通常都會針對每個微服務自行封裝一些客戶端類來包裝這些依賴服務的調用。
所以,Feign在此基礎上做了進一步封裝,由他來幫助我們定義和實現依賴服務接口的定義。在Feign的實現下,我們只需要創建一個接口並使用註解的方式來配置它(以前是Dao接口上面標註Mapper註解,現在是一個微服務接口上面標註一個Feign註解即可),即可完成對服務提供方的接口綁定,簡化了使用Spring Cloud Ribbon時,自動封裝服務調用客戶端的開發量。
Feign集成了Ribbon:
利用Ribbon維護了MicroServiceCloud-Dept的服務列表信息,並且通過輪詢實現了客戶端的負載均衡。
而與Ribbon不同的是,通過feign只需要定義服務綁定接口且以聲明式的方法,優雅而簡單的實現了服務調用。
初步使用
修改microservicecloud-api工程:
添加依賴:
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
新建DeptClientService接口並新增註解@FeignClient
@FeignClient(value = "MICROSERVICECLOUD-DEPT")
public interface DeptClientService {
@RequestMapping(value = "/dept/get/{id}", method = RequestMethod.GET)
Dept get(@PathVariable("id") long id);
@RequestMapping(value = "/dept/list", method = RequestMethod.GET)
List<Dept> list();
@RequestMapping(value = "/dept/add", method = RequestMethod.POST)
boolean add(Dept dept);
}
參考microservicecloud-consumer-dept-80,新建microservicecloud-consumer-dept-feign
添加依賴:
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
microservicecloud-consumer-dept-feign工程修改Controller,添加上一步新建的DeptClientService接口
@RestController
public class DeptController_Consumer {
@Autowired
DeptClientService deptClientService;
@RequestMapping(value = "/consumer/dept/get/{id}")
public Dept get(@PathVariable("id") Long id){
return deptClientService.get(id);
}
@RequestMapping(value = "/consumer/dept/list")
public List<Dept> list(){
return deptClientService.list();
}
@RequestMapping(value = "/consumer/dept/add")
public Object add(Dept dept){
return deptClientService.add(dept);
}
}
microservicecloud-consumer-dept-feign工程修改主啓動類:
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"pers.zhang"}) //開啓Feign
public class DeptCondumerFeign_App {
public static void main(String[] args) {
SpringApplication.run(DeptCondumerFeign_App.class, args);
}
}
測試:
啓動3個eureka集羣
啓動3個部門微服務8001/8002/8003
啓動Feign客戶端微服務
訪問 http://localhost/consumer/dept/list
-
第一次訪問
-
第二次訪問
-
第三次訪問
Feign通過接口的方法調用Rest服務(之前是Ribbon+RestTemplate),該請求發送給Eureka服務器(http://MICROSERVICECLOUD-DEPT/dept/list),通過Feign直接找到服務接口,由於在進行服務調用的時候融合了Ribbon技術,所以也支持負載均衡作用。