DAY53–SpringCloud–Feign
Feign介绍
-(1)Feign的音标
美[feɪn] 假装,装作,佯装
-(2)Feign是什么?
Feign开源库,编写 Http请求
-(3)Feign有什么用?
Feign makes writing java http clients easier
让编写Http请求更容易
,简化拼接url,拼接参数等等操作
-(4)项目主页:https://github.com/OpenFeign/feign
Feign使用
- (1) 使用步骤
- 导入启动器依赖
- 开启Feign功能
- 编写Feign客户端;本质上是一个接口,Feign会生成实现类
- 编写一个处理器ConsumerFeignController,注入Feign客户端并使用
- 测试
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
开启Feign
//@SpringBootApplication
//@EnableDiscoveryClient
//@EnableCircuitBreaker
@SpringCloudApplication //这个注解可以替代以上三个注解
@EnableFeignClients // 开启Feign
public class Demo02ConsumerUser81Application {
编写接口
//调用demo01-provider-user提供者,获取json数据,转成User对象
@FeignClient("demo01-provider-user")
public interface UserClient {
//定义方法
@GetMapping("/user/{id}")
User callProvider(@PathVariable long id);
}
ConsumerController2
@RestController
@RequestMapping("/feign")
@Slf4j
public class ConsumerController2 {
@Autowired
UserClient userClient;
@RequestMapping(path = "/{id}",method = RequestMethod.GET)
public Object get(@PathVariable long id){
User user = userClient.callProvider(id);
return user;
}
}