什么是Feign
Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样。你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做。
Feign是Netflix开发的声明式、模板化的HTTP客户端,其灵感来自Retrofit、JAXRS-2.0以及WebSocket。Feign可帮助我们更加便捷、优雅地调用HTTP API。在Spring Cloud中,使用Feign非常简单——创建一个接口,并在接口上添加一些注解,代码就完成了。Feign支持多种注解,例如Feign自带的注解或者JAX-RS注解等。Spring Cloud对Feign进行了增强,使Feign支持了Spring MVC注解,并整合了Ribbon和Eureka,从而让Feign的使用更加方便。
项目主页:https://github.com/OpenFeign/feign
在pom.xml文件,加入OpenFeign依赖
org.springframework.cloud spring-cloud-starter-openfeign2.2.5.RELEASE
在启动类中,加入@EnableFeignClients的注解
package com.liuyangjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class NacosConsumer8001 {
public static void main(String[] args) {
SpringApplication.run(NacosConsumer8001.class, args);
}
}
在3-nacos-consumer8001项目中新增提供者的API接口
package com.liuyangjava.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(value = "nacos-provider")
public interface NacosConsumerService {
@GetMapping("/nacos/provider")
String getInfoWithFeign();
}
在NacosConsumerController接口中调用Feign
package com.liuyangjava.controller;
import com.liuyangjava.service.NacosConsumerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
public class NacosConsumerController {
@Value("${service-url.nacos-provider}")
private String serverUrl;
@Resource
private NacosConsumerService nacosConsumerService;
@Resource
private RestTemplate restTemplate;
@GetMapping("/nacos/consumer")
public String getInfo() {
return restTemplate.getForObject(serverUrl + "/nacos/provider", String.class);
}
@GetMapping("/nacos/feign/consumer")
public String getInfo2() {
return nacosConsumerService.getInfoWithFeign();
}
}


![[Alibaba微服务技术入门] [Alibaba微服务技术入门]](http://www.mshxw.com/aiimages/31/333095.png)
