Spring Cloud OpenFeign REST服务客户端

时间:2020-09-18 01:54:16   收藏:0   阅读:38

OpenFeign是什么?

OpenFeign是REST服务客户端,REST其实就是HTTP啦,所以OpenFeign其实就是HTTP客户端,那么他和HttpClient有什么不同呢

如何使用OpenFeign

第一步引入OpenFeign

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

第二步启动OpenFeign客户端功能

@SpringBootApplication
@EnableFeignClients
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}  

第三步编写REST服务接口

@FeignClient("stores")
public interface StoreClient {
    @RequestMapping(method = RequestMethod.GET, value = "/stores")
    List<Store> getStores();

    @RequestMapping(method = RequestMethod.POST, value = "/stores/{storeId}", consumes = "application/json")
    Store update(@PathVariable("storeId") Long storeId, Store store);
}  

在@FeignClient中的字符串称为Feign客户端名字,它可以是任意的字符串,它的作用是用来配置Rabbin或Spring Cloud LoadBalancer负载均衡(后面会详细介绍如何做)。

在@FeignClient中还可以设置url参数,它表示提供REST服务的地址,如果你没有设置url参数,那么就要在配置文件中配置。

之后我们就可以把StoreClient注入到我们需要使用的地方啦。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!