1.使用Feign实现远程HTTP调用
Feign:是一个声明式WebService客户端.使用Feign能让编写WebService客户端更加简单
1.Feign的使用
pom文件添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启动类添加注解
@EnableFeignClients
添加feignClient文件
注意使用Feign的时候,如果参数中带有@PathVariable形式的参数,则要用value=""标明对应的参数,否则会抛出IllegalStateException异常*
修改请求代码
2.Feign的组成
3.Feign的日志设置和级别
代码配置方法
添加Feign日志配置类
这个类 别加 @Configuration注解 (会导致父子上下文重复问题)
Feign请求文件添加配置
yml文件添加Feign请求文件全路径
必须为设置为 debug
级别才才会输出日志
logging:
level:
com.itkk.contentcenter.feignclient.UserCenterFeignClient: debug
运行查看控制台输出的Feign日志
全局配置方法
修改器启动类的@EnableFeignClients
注解,添加defaultConfiguration
属性
@EnableFeignClients(defaultConfiguration = UserCenterFeignConfiguration.class)
yml文件配置方法
直接在yml文件配置即可
全局配置方法
将指定的user-center改为default即可
4.Feign支持的配置项
使用代码
支持的配置项如下
使用属性
支持的配置项如下
5.Ribbon和Feign的配置对比
5.Feign的继承
Feign的继承存在很大的争议
现状: 官方不支持使用,但是很多企业在使用
6.Feign多参数请求
GET请求示例
在请求参数前加上@SpringQueryMap
@GetMapping("/get")
UserDTO query(@SpringQueryMap UserDTO userDTO);
POST请求示例
在请求参数前加上@RequestBody
@RequestMapping(value = "/post", method = RequestMethod.POST)
public User post(@RequestBody User user);
7.Feign脱离ribbon的使用
// 脱离ribbon的使用
@FeignClient(name = "baidu", url = "http://www.baidu.com")
public interface TestBaiduFeignClient {
@GetMapping("")
String index();
}
8.RestTemplate和Feign的对比
9.优化Feign的性能
使用httpclient连接池可以让Feign提升15%左右的性能
1.pom添加依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2.yml里启用连接池,配置连接池数量
feign:
httpclient:
enabled: true
# feign的最大连接数
max-connections: 200
# feign单个路径的最大连接数
max-connections-per-route: 50
未完待续!!!
上一篇: 练习Spring Cloud Alibaba —— 2.
下一篇: 练习Spring Cloud Alibaba —— 4.