Feign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用Feign, 我们可以做到使用HTTP请求远程服务时能与调用本地方法一样的编码体验,开发者完全感知不到这是远程方法,更感知不到这是个HTTP请求。比如:
首先微服务ProductApplication 中加入 @EnableFeignClients
package com.cloud.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class ProductApplication {
public static void main(String[] args){
SpringApplication.run(ProductApplication.class,args);
}
}
关于微服务Product 中Controller
package com.cloud.product.controller;
import com.cloud.product.feign.ApiGetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/index")
public class ProductController {
@Autowired
ApiGetService apiGetService;
@GetMapping("/hello")
public String hello() {
return "product say hello";
}
@GetMapping("/testFeign")
public String feignApiGeteWay() {
return apiGetService.testApiHello();
}
}
采用Feign 相关配置如下
package com.cloud.product.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "API-GATEWAY")
public interface ApiGetService {
@GetMapping("/api/hello")
String testApiHello();
}
API-GATEWAY是注册在EUREKA中的服务,/api/hello 是该微服务下的接口
请求微服务中PRODUCT 的 /testFeign接口即可调用 微服务API-GATEWAY 服务下 /api/hello
总结
通过Feign, 我们能把HTTP远程调用对开发者完全透明,得到与调用本地方法一致的编码体验。这一点与阿里Dubbo中暴露远程服务的方式类似,区别在于Dubbo是基于私有二进制协议,而Feign本质上还是个HTTP客户端。如果是在用Spring Cloud Netflix搭建微服务,那么Feign无疑是最佳选择。