介绍
声明式的http客户端,底层还是HttpClient,可以解决RestTemplate硬编码进行远程服务调用的缺点
官网:https://github.com/OpenFeign/feign
入门
以A微服务对B微服务远程调用为例
若无多个微服务对B微服务调用的情况,第1、2步可在A微服务中完成
1.建立Feign模块并导入依赖
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
复制代码 2.编写Feign的客户端BClient
BClient添加注解:@B
@B为B在nacos中的注册名
在使用Feign客户端接口时,强烈建议遵守如下几点要求:
- 使用@RequestMapping注解
古早版本只能识别@RequestMapping,便于与古早版本兼容
- 请求参数需要指定参数名称
- @FeignClient("BClient")
- public interface BClient {
- @RequestMapping("/user/{id}")
- void findById(@PathVariable("id") Long id);
- }
复制代码 3.A引导类增加注解
@EnableFeignClients(basePackages = {"BClient所在目录绝对路径"})
4.远程调用
注入BClient便可直接调用- @Autowired
- private BClient bClient;
- public void findById(Long id){
- bClient.findById(id);
- }
复制代码 #.Feign集成HttpClient(非必须)
- A微服务中导入依赖
- <dependency>
- <groupId>io.github.openfeign</groupId>
- <artifactId>feign-httpclient</artifactId>
- </dependency>
复制代码 - 配置文件
- feign:
- httpclient:
- enabled: true # 开启feign对HttpClient的支持
- max-connections: 200 # 最大的连接数
- max-connections-per-route: 50 # 每个路径的最大连接数
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |