本篇主要讲解什么是Feign,以及Feign入门实践
Feign是一个声明式的Web Service客户端,整合了注解,所以使用起来比较方便,通过它调用HTTP请求访问远程服务,就像访问本地方法一样简单开发者完全无感知
Feign原理:我们首先会添加@EnableFeignClients注解开启对 FeignClient扫描加载处理,扫描后会注入到SpringIOC容器,当定义的feign接口方法被调用时,通过JDK代理的方式,生成具体的RequestTemplate,RequestTemplate生成Request,交给URLConnection处理,并结合LoadBalanceClient与Ribbon,以负载均衡的方式发起服务间的调用
1.Feign具有以下一些重要特性:
- 整合了Hystrix,支持fallback容错降级
- 整合了Ribbon,直接请求的负载均衡
- 支持HTTP请求和响应的压缩
- 使用OkHttp替换原生URLConnection,提高效率
2.创建项目,快速开始
本篇入门实践不依赖注册中心等其他组件,后面Feign的高级使用篇会整合注册中心,本篇的主要目的是通过 FeignClient 指定调用URL的方式,查询GitHub上的仓库信息
- 新建个maven工程,再添加Module,类型为Spring Initializr,也就是SpringBoot的项目,添加Feign的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 在启动主类上添加@EnableFeignClients,启用Feign
@EnableFeignClients
@SpringBootApplication
public class SimplefeignApplication {
public static void main(String[] args) {
SpringApplication.run(SimplefeignApplication.class, args);
}
}
- 先确定要访问的GitHub api是否能查询到信息,在浏览器输入该地址:https://api.github.com/search/repositories?q=spring-cloud ,查询出有30024条与spring-cloud相关数据
- 接下来是关键的 FeignClient的使用了,新建一个接口类IIndexFeignService
//指定了url就会访问该url地址,否则会把name参数当作服务名到注册中心中查询该名字服务,此时指定了url后可以随意命名
@FeignClient(name = "search-github" , url = "https://api.github.com")
public interface IIndexFeignService {
@RequestMapping(value = "/search/repositories" , method = RequestMethod.GET)
String search(@RequestParam("q") String query);
}
- 新建一个 IndexController ,注入IIndexFeignService,访问search方法
@RestController
public class IndexController {
@Autowired private IIndexFeignService feignService;
@RequestMapping(value = "/search" , method = RequestMethod.GET)
public String search(@RequestParam("query") String query){
return feignService.search(query);
}
}
启动项目,访问:http://localhost:8080/search?query=spring-cloud ,可以看到返回的total_count与上面直接输入url地址是一样的,ok,feign入门实践大功告成
代码已上传至码云,源码,项目使用的版本信息如下:
- SpringBoot 2.0.6.RELEASE
- SpringCloud Finchley.SR2(非常新的版本)