天天看点

微服务【SpringCloud】--FeignFeign介绍Feign使用

文章目录

  • Feign介绍
    • (1)Feign的音标
    • (2)Feign是什么?
    • (3)Feign有什么用?
    • (4)项目主页:https://github.com/OpenFeign/feign
  • Feign使用
    • pom.xml
    • 开启
    • 接口
    • CustomerController2

Feign介绍

(1)Feign的音标

美[feɪn] 假装,装作,佯装

(2)Feign是什么?

Feign开源库,编写 Http请求

(3)Feign有什么用?

Feign makes writing java http clients easier

s让编写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>

           

开启

@EnableFeignClients//开启feign
@SpringCloudApplication
public class Demo02ConsumerUser81Application
           

接口

//String url = "http://demo01-provider-user/users/"+id;
//调用demo01-provider-user提供者,获取json数据,转成User对象
@FeignClient("demo01-provider-user")
public interface UserClient {
    //定义方法
     @GetMapping("/users/{id}")
     User callProvider(@PathVariable long id);
}
           

CustomerController2

@RestController
@RequestMapping("/feign")
@Slf4j
public class CustomerController2 {
    @Autowired
    UserClient userClient;
    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    public Object get(@PathVariable long id) throws InterruptedException {
        User user = userClient.callProvider(id);
        return user;
    }

}