一、Feign簡介
Feign是一種聲明式的RESTful客戶端,可以與Spring Cloud Eureka和Spring Cloud Ribbon進行整合,以提供負載均衡的HTTP客戶端實現。使用Feign可以使得編寫RESTful客戶端變得更加簡單,Feign依據RESTful服務的接口定義去生成相關的HTTP客戶端,開發人員只需要定義接口,然後使用Java的Annotation去描述接口定義,Feign會根據這些Annotation自動生成相關的代理實現。
Feign可以通過Ioc容器(如Spring Boot)去使用,使用Feign遠程調用RESTful接口的代碼非常簡單,只需要定義接口並添加相關註解即可。
二、使用Feign調用RESTful服務
使用Feign進行RESTful服務調用包含以下三個步驟:
第一步:添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
第二步:創建Feign代理接口
在Spring Boot工程中,定義Feign接口的方法就相當於定義一個Feign客戶端,在實現接口中通過配置URL實現「遠程調用」。
@FeignClient(name = "xxxx")
public interface DemoFeignService {
@RequestMapping(value = "/demo/xxx", method = RequestMethod.GET)
String xxx();
@RequestMapping(value = "/demo/yyy", method = RequestMethod.GET)
String yyy(@RequestParam("name") String name);
}
這裡需要注意的是,在Feign接口的定義中使用了Spring MVC的註解,包括RequestMapping和RequestParam,同時使用了FeignClient定義了一個客戶端的名稱,這個名稱對應了遠端服務在Eureka上的註冊名稱。
第三步:使用Feign代理接口
可以在控制器中使用@Autowired的方式來注入Feign接口,然後直接調用該接口的相關方法,就實現了RESTful服務的調用。
@RestController
public class DemoController {
@Autowired
private DemoFeignService demoFeignService;
@RequestMapping("/demo")
public String demo() {
return demoFeignService.xxx();
}
@RequestMapping("/demo/{name}")
public String demo(@PathVariable String name) {
return demoFeignService.yyy(name);
}
}
三、使用Spring Boot集成Feign和Ribbon實現負載均衡
我們可以通過SpringBoot和Feign的組合實現負載均衡。Feign默認整合了Eureka和Ribbon,因此使用起來非常簡單。需要注意的是需要先引入Spring Cloud Eureka的依賴。
第一步:添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
第二步:添加註解@EnableFeignClients和@EnableEurekaClient
在Spring Boot啟動類上添加@EnableFeignClients註解啟用Feign,同時添加@EnableEurekaClient註解啟用註冊中心客戶端。
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
第三步:使用Feign和Ribbon實現負載均衡
使用Feign和Ribbon實現負載均衡,只需要在Feign接口定義上添加一個serviceId屬性用於標識服務的名稱。Feign會自動通過Ribbon和Eureka去獲取遠程服務的地址。
@FeignClient(serviceId = "demo-service")
public interface DemoFeignService {
@RequestMapping(value = "/demo/xxx", method = RequestMethod.GET)
String xxx();
@RequestMapping(value = "/demo/yyy", method = RequestMethod.GET)
String yyy(@RequestParam("name") String name);
}
以上為使用SpringBoot和Feign實現RESTful服務調用的完整思路。當然,實際應用中需要建立相應的服務註冊中心,進行服務發現。這裡只是提供了最基礎的實現方式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/190695.html